Lecture 8a: File I/O BJ Furman 21MAR2011
Learning Objectives Explain what is meant by a data stream Explain the concept of a ‘file’ Open and close files for reading and writing
Data Streams Data ‘stream’ “an ordered series of bytes” (Darnell and Margolis, 1996) Like a 1D array of characters that can flow from your program to a device or file or vice-versa IO involves reading data from or writing data to a stream Prior to UNIX Programmers had to handle all the intricacies and complexities of interfacing to input and output devices, such as card readers, printers, terminals, etc. UNIX Abstracted away the details of IO to the concept of the data stream Established standard data streams: stdin – data coming into your program (usually from the keyboard) stdout – data going out of your program (usually to the display) stderr – for error information going out of your program
File IO Need to first associate a stream with a file or device Three streams are automatically opened and associated with your program: stdin, stdout, stderror Ex. printf() defaults to printing to the display To read from or write to another file stream, you need to declare a pointer to a data structure called FILE This pointer is used to read from, write to, or close the stream Use IO functions for file operations (like fprintf())
Opening a File - 1 Key steps: Declare a pointer to FILE FILE *fp; Provides the means to associate a file with a data stream Will be used by other functions such as fprintf() Use fopen() function with a path to the file and a file mode as arguments Ex. Open file_name.txt to be able to read from it fp = fopen(“file_name.txt”, “r”); fopen() returns a pointer to the file fp stores the pointer to the file, file_name.txt “r” opens the file for reading from Can also open a file to write to it or append to it See reference:
Opening a File - 2 Other modes Good idea to test that the file was opened without error fopen() will return NULL if there is an error opening the file fp = fopen(“file_name.txt”, “r”); if(fp == NULL) { printf("Error: can't open file to read\n"); return 1; } Source:
Closing a File Function header: int fclose(FILE *fp); Good idea to test the file was closed without error Test the return value of fclose fclose() will return EOF if there is an error closing the file if(fclose(fp) == EOF) { printf("Error closing file\n"); return 1; } It is best practice to close all files that you opened, somewhere in your program
Arrays and File I/O Arrays are often used with data consisting of many elements Often too tedious to handle I/O by keyboard and monitor File I/O is used instead File I/O and array example file_I_O.c
Review
References Darnell, P. A. & Margolis, P. E. (1996) C, a software engineering approach, 3 rd ed., Springer, New York, p Visited 23OCT Visited 23OCT