This preview has intentionally blurred sections. Sign up to view the full version.View Full Document
Unformatted text preview: Intro to File Input/Output in C 1. Redirection: One way to get input into a program or to display output from a program is to use standard input and standard output , respectively. All that means is that to read in data, we use scanf() (or a few other functions) and to write out data, we use printf() . When we need to take input from a file (instead of having the user type data at the keyboard) we can use input redirection: % a.out < inputfile This allows us to use the same scanf() calls we use to read from the keyboard. With input redirection, the operating system causes input to come from the file (e.g., inputfile above) instead of the keyboard. Similarly, there is output redirection : % a.out > outputfile that allows us to use printf() as before, but that causes the output of the program to go to a file (e.g., outputfile above) instead of the screen. Of course, the 2 types of redirection can be used at the same time... % a.out < inputfile > outputfile 2. C File I/O: While redirection is very useful, it is really part of the operating system (not C). In fact, C has a general mechanism for reading and writing files, which is more flexible than redirection alone. stdio.h There are types and functions in the library stdio.h that are used for file I/O. Make sure you always include that header when you use files. Type For files you want to read or write, you need a file pointer, e.g.: FILE *fp; What is this type " FILE * "? Realistically, you don't need to know. Just think of it as some abstract data structure, whose details are hidden from you. In other words, the only way you can use a FILE * is via the functions that C gives you. Note: In reality, FILE is some kind of structure that holds information about the file. We must use a FILE * because certain functions will need to change that information, i.e., we need to pass the information around by reference . Functions Reading from or writing to a file in C requires 3 basic steps: 1. Open the file. 2. Do all the reading or writing. 3. Close the file. Following are described the functions needed to accomplish each step. A complete program that includes the example described below, plus an input file to use with that program, is available to download . 3. Opening a file: In order to open a file, use the function fopen() . Use it as: fp = fopen( filename , mode ); where: 1. filename is a string that holds the name of the file on disk (including a path like /cs/course if necessary)....
View Full Document
- Summer '11
- Input/output, Standard streams, standard output