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. mode is used to determine how the file will be treated (i.e. for input, output, etc).
If there is an error, fopen() returns NULL.
Mode | Meaning | Already Exists | Does Not Exist |
---|---|---|---|
“r” | Open a file for reading | read from start | error |
“w” | Create a file for writing | destroy contents | create new |
“a” | Append to a file | write to end | create new |
“r+“ | Open a file for read/write | read from start | error |
“w+“ | Create a file for read/write | destroy contents | create new |
“a+“ | Open a file for read/write | write to end | create new |
You can also optionally specify the “b” flag to open a file in binary mode on Windows systems. This flag is ignored on POSIX systems (including Linux), so it's safe to always specify this flag when operating on binary files.
If the mode contains “a” data is written to the end of the file regardless of the current position of the file pointer.
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