Opening and Closing a Stream
The fopen() and fclose() library routines can be called to open and close a file stream:
#include <stdio.h> FILE *fopen(const char *filename, const char *mode); int fclose(FILE *stream);
The mode argument points to a string that starts with one of the following sequences. Note that these sequences are part of the ANSI C standard.
r, rb. Open the file for reading.
w, wb. Truncate the file to zero length or, if the file does not exist, create a new file and open it for writing.
a, ab. Append to the file. If the file does not exist, it is first created.
r+, rb+, r+b. Open the file for update (reading and writing).
w+, wb+, w+b. Truncate the file to zero length or, if the file does not exist, create a new file and open it for update (reading and writing).
a+, ab+, a+b. Append to the file. If the file does not exist it is created and opened for update (reading and writing). Writing will start at the end of file.
Internally, the standard I/O library will map these flags onto the corresponding flags to be passed to the open() system call. For example, r will map to O_RDONLY, r+ will map to O_RDWR and so on. The process followed when opening a stream is shown in Figure 4.1.
The following example shows the effects of some of the library routines on the FILE structure:

Figure 4.1 Opening a file through the stdio library.
1 #include <stdio.h> 2 3 main() 4 { ...