fopen()

This is a File I/O function. It is not implemented in the 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 (i.e., 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 file opening function, fopen()
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, appending all writes to the end.

If the mode contains an " r", but the file does not 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 the file could not be created, the function returns NULL.

See also

fclose(),

freopen(),

setbuf() and

setvbuf()