Name

fopen

Synopsis

Opens a file

#include <stdio.h>
FILE *fopen( const char * restrict name, const char * restrict mode );

The fopen() function opens the file with the specified name. The second argument is a character string that specifies the requested access mode. The possible values of the mode string argument are shown in Table 17-1.

fopen() returns the FILE pointer for you to use in subsequent input or output operations on the file, or a null pointer if the function fails to open the file with the requested access mode.

Table 17-1. File access modes

Mode string

Access mode

Notes

“r”

“r+”

Read

Read and write

The file must already exist.

“w”

“w+”

Write

Write and read

If the file does not exist, fopen() creates it. If it does exist, fopen() erases its contents on opening.

“a”

“a+”

Append

Append and read

If the file does not exist, fopen() creates it.

When a file is first opened, the file position indicator points to the first byte in the file. If a file is opened with the mode string "a" or "a+", then the file position indicator is automatically placed at the end of the file before each write operation, so that existing data in the file cannot be written over.

If the mode string includes a plus sign, then the mode allows both input and output, and you must synchronize the file position indicator between reading from and writing to the file. Do this by calling fflush() or a file positioning function—fseek(), fsetpos(), or rewind()—after writing and before reading, and by calling a file-positioning function ...

Get C in a Nutshell now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.