Jump to content

C++ Programming/Code/Standard C Library/Functions/fopen

From Wikibooks, open books for an open world

fopen

[edit | edit source]
Syntax
#include <cstdio>
FILE *fopen( const char *fname, const char *mode );

The fopen() function opens a file indicated by fname and returns a stream associated with that file. If there is an error, fopen() returns NULL. mode is used to determine how the file will be treated (i.e. for input, output, etc.)

The mode contains up to three characters. The first character is either "r", "w", or "a", which indicates how the file is opened. A file opened for reading starts allows input from the beginning of the file. For writing, the file is erased. For appending, the file is kept and writing to the file will start at the end. The second character is "b", is an optional flag that opens the file as binary - omitting any conversions from different formats of text. The third character "+" is an optional flag that allows read and write operations on the file (but the file itself is opened in the same way.

Mode Meaning Mode Meaning
"r" Open a text file for reading "r+" Open a text file for read/write
"w" Create a text file for writing "w+" Create a text file for read/write
"a" Append to a text file "a+" Open a text file for read/write
"rb" Open a binary file for reading "rb+" Open a binary file for read/write
"wb" Create a binary file for writing "wb+" Create a binary file for read/write
"ab" Append to a binary file "ab+" Open a binary file for read/write

An example:

int ch;
FILE *input = fopen( "stuff", "r" );
ch = getc( input );
Related topics
fclose - fflush - fgetc - fputc - fread - freopen - fseek - fwrite - getc - getchar - setbuf