CSC209H Lecture 3. Dan Zingaro. January 21, 2015

Similar documents
File IO and command line input CSE 2451

structs as arguments

Slide Set 8. for ENCM 339 Fall 2017 Section 01. Steve Norman, PhD, PEng

PROGRAMMAZIONE I A.A. 2017/2018

Content. Input Output Devices File access Function of File I/O Redirection Command-line arguments

25.2 Opening and Closing a File

UNIT-V CONSOLE I/O. This section examines in detail the console I/O functions.

File Access. FILE * fopen(const char *name, const char * mode);

Fundamentals of Programming. Lecture 10 Hamed Rasifard

2009 S2 COMP File Operations

Lecture 7: file I/O, more Unix

System Programming. Standard Input/Output Library (Cont d)

Input/Output and the Operating Systems

Programming in C. Session 8. Seema Sirpal Delhi University Computer Centre

Lecture 03 Bits, Bytes and Data Types

CS240: Programming in C

CSI 402 Lecture 2 Working with Files (Text and Binary)

M.CS201 Programming language

Introduction to C Programming (Part C) Copyright 2008 W. W. Norton & Company. All rights Reserved

Important Dates. October 27 th Homework 2 Due. October 29 th Midterm

Midterm Exam Nov 8th, COMS W3157 Advanced Programming Columbia University Fall Instructor: Jae Woo Lee.

File I/O. Preprocessor Macros

C-Refresher: Session 10 Disk IO

Lecture 12 CSE July Today we ll cover the things that you still don t know that you need to know in order to do the assignment.

CSE 12 Spring 2016 Week One, Lecture Two

This code has a bug that allows a hacker to take control of its execution and run evilfunc().

Topic 8: I/O. Reading: Chapter 7 in Kernighan & Ritchie more details in Appendix B (optional) even more details in GNU C Library manual (optional)

Final Exam. Fall Semester 2016 KAIST EE209 Programming Structures for Electrical Engineering. Name: Student ID:

CSC 270 Survey of Programming Languages. Input and Output

Computer programming

Mode Meaning r Opens the file for reading. If the file doesn't exist, fopen() returns NULL.

File (1A) Young Won Lim 11/25/16

COSC Software Engineering. Lecture 16: Managing Memory Managers

CMPE-013/L. File I/O. File Processing. Gabriel Hugh Elkaim Winter File Processing. Files and Streams. Outline.

Lecture 7: Files. opening/closing files reading/writing strings reading/writing numbers (conversion to ASCII) command line arguments

Naked C Lecture 6. File Operations and System Calls

Recitation 2/18/2012

Introduction to Programming in C Department of Computer Science and Engineering. Lecture No. #47. File Handling

Lecture 8: Structs & File I/O

Final Exam. Fall Semester 2016 KAIST EE209 Programming Structures for Electrical Engineering. Name: Student ID:

CSE2301. Introduction. Streams and Files. File Access Random Numbers Testing and Debugging. In this part, we introduce

CSCI-243 Exam 2 Review February 22, 2015 Presented by the RIT Computer Science Community

Standard File Pointers

Quick review of previous lecture Ch6 Structure Ch7 I/O. EECS2031 Software Tools. C - Structures, Unions, Enums & Typedef (K&R Ch.

Operating System Labs. Yuanbin Wu

C programming basics T3-1 -

Chapter 5, Standard I/O. Not UNIX... C standard (library) Why? UNIX programmed in C stdio is very UNIX based

fopen() fclose() fgetc() fputc() fread() fwrite()

CS 220: Introduction to Parallel Computing. Input/Output. Lecture 7

Introduction to file management

CSE 410: Systems Programming

BIL 104E Introduction to Scientific and Engineering Computing. Lecture 12

ECE551 Midterm Version 1

ECE264 Spring 2014 Exam 2, March 11, 2014

Systems Programming. 08. Standard I/O Library. Alexander Holupirek

CS113: Lecture 7. Topics: The C Preprocessor. I/O, Streams, Files

CSE 333 SECTION 3. POSIX I/O Functions

CSE 12 Spring 2018 Week One, Lecture Two

Accessing Files in C. Professor Hugh C. Lauer CS-2303, System Programming Concepts

C mini reference. 5 Binary numbers 12

System Software Experiment 1 Lecture 7

Pointers and File Handling

Programming & Data Structure

CSci 4061 Introduction to Operating Systems. Input/Output: High-level

Understanding Pointers

THE C STANDARD LIBRARY & MAKING YOUR OWN LIBRARY. ISA 563: Fundamentals of Systems Programming

Arrays and Pointers in C. Alan L. Cox

File Handling. 21 July 2009 Programming and Data Structure 1

CS240: Programming in C

Programming in C. 4. Misc. Library Features, Gotchas, Hints and Tips. Dr. Neel Krishnaswami University of Cambridge

File Handling. Reference:

University of Calgary Department of Electrical and Computer Engineering ENCM 335 Instructor: Steve Norman

Intermediate Programming, Spring 2017*

UNIX System Programming

ECE 264 Exam 2. 6:30-7:30PM, March 9, You must sign here. Otherwise you will receive a 1-point penalty.

C Syntax Arrays and Loops Math Strings Structures Pointers File I/O. Final Review CS Prof. Jonathan Ventura. Prof. Jonathan Ventura Final Review

8. Characters, Strings and Files

Lab # 4. Files & Queues in C

o Code, executable, and process o Main memory vs. virtual memory

Contents. A Review of C language. Visual C Visual C++ 6.0

File I/O. Arash Rafiey. November 7, 2017

EL2310 Scientific Programming

CSCI-243 Exam 1 Review February 22, 2015 Presented by the RIT Computer Science Community

7/21/ FILE INPUT / OUTPUT. Dong-Chul Kim BioMeCIS UTA

Computer Programming Unit v

C Basics And Concepts Input And Output

ECE551 Midterm Version 1

Binghamton University. CS-211 Fall Input and Output. Streams and Stream IO

Stream Model of I/O. Basic I/O in C

UNIT IV-2. The I/O library functions can be classified into two broad categories:

CS61, Fall 2012 Section 2 Notes

Computer System and programming in C

PRINCIPLES OF OPERATING SYSTEMS

Computer Programming: Skills & Concepts (CP) Files in C

EL2310 Scientific Programming

CS11001/CS11002 Programming and Data Structures (PDS) (Theory: 3-0-0)

High-performance computing and programming Intro to C on Unix/Linux. Uppsala universitet

Fundamental of Programming (C)

Processes. Johan Montelius KTH

UNIX Shell. The shell sits between you and the operating system, acting as a command interpreter

Transcription:

CSC209H Lecture 3 Dan Zingaro January 21, 2015

Streams (King 22.1) Stream: source of input or destination for output We access a stream through a file pointer (FILE *) Three streams are available without us doing anything stdin: standard input (keyboard unless redirected) stdout: standard output (screen unless redirected) stderr: standard error (screen unless redirected) To use other streams, we can open files

Opening and Closing Files (King 22.2) #include <stdio.h> //mode r=read, w=write, a=append FILE *fopen(const char *filename, const char *mode); int fclose(file *stream); fopen returns NULL if it fails fclose returns EOF if it fails When a function call fails, we must detect it or the program will keep running and crash much later

Error-Handling System and library calls often return a special value (NULL, EOF, -1, etc.) to indicate an error If there is an error, they set variable errno to a positive integer error number errno is initialized to 0 when the program starts running If a call fails, the value of errno is meaningful

Perror void perror (char *str); perror writes the following to standard error: str, a colon, and an English description of the value in errno Protocol Check whether a system/library call returns an error (usually -1 or sometimes NULL) If so, call perror (and possibly exit)

Perror... #include <stdio.h> #include <stdlib.h> #define FILENAME "example.dat" int main(void) { FILE *fp; fp = fopen(filename, "r"); if (fp == NULL) { perror("fopen"); exit(1); } fclose(fp); // should probably perror this too! return 0; }

Commandline Arguments int main(int argc, char *argv[]) { If we define main like that, then: argv[0] is the program name argv[1],..., argv[argc - 1] are the arguments argc is the number of arguments For anything more than simple filenames, use getopt to process arguments!

Commandline Arguments... #include <stdio.h> #include <stdlib.h> int main(int argc, char *argv[]) { FILE *fp; if (argc!= 2) { fprintf(stderr, "Usage: %s filename\n", argv[0]); exit(1); } if ((fp = fopen(argv[1], "r")) == NULL) { printf("%s cannot be opened.\n", argv[1]); exit(1); } printf("%s can be opened.\n", argv[1]); return 0; }

Block I/O (King 22.6) //Read num_elem elements of size elem_size into ptr size_t fread(void *ptr, size_t elem_size, size_t num_elem, FILE *stream); //Write num_elem elements of size elem_size to file size_t fwrite(const void *ptr, size_t elem_size, size_t num_elem, FILE *stream); fread and fwrite can be used to read and write binary data They re often used to read from a file into an array or write an array to a file They return the number of elements (not bytes!) read or written

Example: Block I/O #include <stdio.h> #include <stdlib.h> int main(void) { short nums[] = {5, 200, 1000}; FILE *fp; if ((fp = fopen("example.dat", "w")) == NULL) { perror("fopen"); exit(1); } fwrite(nums, sizeof(short), 3, fp); fclose(fp); return 0; }

Types of Buffering (King 22.2) Unbuffered: output appears immediately (e.g. stderr) Line buffered: output appears when a whole line has been written (e.g. stdout when it is the screen) Block buffered: output appears when the buffer is filled (e.g. files) Use stderr for your fprintf debugging or your code will crash before you see your output!

Automatic Memory Allocation Suppose we want to write a convenience function that allocates and initializes an array of integers We tell it how many integers to allocate, and it returns a pointer to the beginning of the array int *nums; nums = make_array(10); // now nums is an array of 10 0 s

Automatic Memory Allocation... Here is an attempt at writing this function. int *make_array(int num_elements) { int array[num_elements]; int i; for (i = 0; i < num_elements; i++) array[i] = 0; return array; }

Automatic Memory Allocation... The problem is that array goes out of scope when the function returns The memory for array exists only while make_array is running, after which that memory is reclaimed What we have to be able to do is allocate memory that will not be lost when make_array finishes In other words, we require manual control of memory allocation

Dynamic Memory Allocation (King Ch 17) There s one other problem we have to allocate new memory each time the function is called to store the new array But when the program is being compiled, we can t possibly know how many times make_array will be called Therefore, we do not know how much memory to reserve at compile-time We must dynamically allocate memory while the program is running

Malloc void *malloc (size_t size); We use malloc to dynamically allocate memory malloc returns a pointer to the newly acquired memory, or NULL if there is not enough available memory To allocate memory for an array of n integers, we ask malloc for n times the size of an integer... int *nums; nums = malloc (n * sizeof(int));

Malloc... int *nums; nums = malloc (n * sizeof(int)); nums is now a pointer to an uninitialized array of n integers We can use it like any array nums[0] = 90; nums[1] = 50; nums 90 50...

A Correct make array Function int *make_array(int num_elements) { int *array = malloc(num_elements * sizeof(int)); int i; for (i = 0; i < num_elements; i++) array[i] = 0; return array; }

Freeing Memory Once we use malloc to ask for memory, we re responsible for releasing it when it s no longer required When we don t use malloc, memory is freed automatically when it goes out of scope So, when we re finished with the array, we should release its memory If we keep calling malloc without freeing any of the memory, memory will eventually run out of memory free (nums);

Lost Memory p = malloc(...); q = malloc(...); p q block1 block2 p = q; p q block1 block2 Since p now points to q s block, we have no way of accessing p s old block This is called a memory leak

Dangling Pointers int *p = malloc(5 * sizeof(int));... free(p); p is now a pointer to memory it does not own; it is an error to access memory through p p[0] = 0; // trouble p 90 50...

Java Comparison In Java: Set s; //Memory allocated for pointer s s = new HashSet(); //Memory allocated for a HashSet object In C: int *a; //Memory allocated for pointer a a = malloc(10 * sizeof(int)); //Memory for 10 ints