7.1. 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 close the file.
- To do this we need the notion of a file descriptor, which is our means of accessing the file.
- There are two types of file descriptors.
- Low level functions open(), read(), write(), close() use int file descriptors. – Considered more difficult to use.
- stdio.h defines a typedef for a special data structure which is the file descriptor we will discuss.
- We have already used two file descriptors: stdin and stdout to do I/O from the terminal. Another related file descriptor is stderr. stderr can be used to report errors or warnings that are not part of stdout. The int file descriptors for stdin, stdout, stderr are 0, 1, 2.
7.2. File I/O example¶
-
fgets
()¶
-
fprintf
()¶
-
fscanf
()¶
FILE *fp;
char buff[SIZE];
fp = fopen( "filename", "r+" ); /* filename could be supplied by a
string instead of a constant. */
fgets( buff, SIZE, fp ); /* used in ReadLine */
fprintf( fp, "format", ...);
fscanf( fp, "format", ...);
fclose(fp);
See also