2.14. File I/O¶
- Objective: Read and write to/from files like what we have done from the terminal.
- Need to open a file, perform I/O, and then close the file.
- To do this we need the notion of a file descriptor, which is our means of accessing the file.
- The file descriptor is a pointer of type (FILE *), which is a pointer to a data structure. See File I/O for more information.
- fopen("filename", "[rw]") is the function we will use for opening files. See fopen modes for more information.
- With an open file, we can use
fscanf()
,fprintf()
,fgets()
and other file I/0 functions. - We use fclose( FILE * ) to close an open file.
- Don’t worry if you find this confusing at this time. We will cover file I/O in much more detail later.
2.14.1. File I/O examples¶
FILE *fin, *fout; char buff[SIZE]; fin = fopen( "filename", "r" ); /* filename could be supplied by a string instead of a constant. */ fout = fopen( "filename", "w" ); fgets( buff, SIZE, fin ); fscanf( fin, "format", ...); fprintf( fout, "format", ...); fclose(fin); fclose(fout);
Now complete Homework 5 - Mean and Standard Deviation of Numbers.