fopen()

This is a file I/O function, also hardware dependent. It is not implemented in this Compiler.

Syntax
  #include <stdio.h>

  
  FILE *fopen(const char *name, const char *mode);

  
Description

fopen() opens a file with the given name and mode. It automatically allocates an I/O buffer for the file.

There are three main modes: read, write, and update (both read and write) accesses. Each can be combined with either text or binary mode to read a text file or update a binary file. Opening a file for text accesses translates the end-of-line character (combination) into '\n' when reading and vice versa when writing. The following table lists all possible modes.

Table 1. Operating Modes of the fopen() Function
Mode Effect
r Open the file as a text file for reading.
w Create a text file and open it for writing.
a Open the file as a text file for appending.
rb Open the file as a binary file for reading.
wb Create a file and open as a binary file for writing.
ab Open the file as a binary file for appending.
r+ Open a text file for updating.
w+ Create a text file and open for updating.
a+ Open a text file for updating. Append all writes to the end.
r+b or rb+ Open a binary file for updating.
w+b or wb+ Create a binary file and open for updating.
a+b or ab+ Open a binary file for updating. Append all writes to the end.

If the mode contains an r, but the file doesn't exist, fopen() returns unsuccessfully. Opening a file for appending (mode contains a) always appends writing to the end, even if fseek(), fsetpos(), or rewind() is called. Opening a file for updating allows both read and write accesses on the file. However, fseek(), fsetpos(), or rewind() must be called in order to write after a read or to read after a write.

Return

A pointer to the file descriptor of the file. If fopen() cannot create the file, the function returns NULL.

See also

fclose()

freopen()

setbuf()

setvbuf()