The standard C library provides functions for writing input and output to files.
Most of the file input/output functions are declared in header stdio.h. Add the line
#include <stdio.h> to your source code to use file I/O functions.
fopen() is used to open a file.
The function declaration changed in C99, by adding the keyword restrict. Before C99 it was:
FILE *fopen(const char *filename, const char *mode);
In C99 and above:
FILE *fopen(const char *restrict filename, const char *restrict mode);
filename: Null-terminated string of the filename to associate the data to mode: Null-terminated string that determines the file access mode
|mode||Stands For||Description||Behaviour If File Already Exists||Behaviour If File Doesn't Exist\|
|"r"||read||Open a file to read from it.||Read from start.||Error.|
|"w"||write||Open a file to write to it.||Delete file contents.||Create new file.|
|"wx"||write||Write to file, but don't overwrite if file already exists.||Error.||Create new file|
|"a"||append||Open a file to append data to the end.||Append new data to the end of file.||Create new file.|
|"r+"||read extended||Opens a file for read/write access||Read from start.||Error.|
|"w+"||write extended||Creates a file for read/write access||Deletes file contents.||Create new file.|
|"w+x"||write extended||Opens a file for read/write access, but doesn't overwrite if file already exists.||Error.||Create new file.|
|"a+"||append extended||Opens a file for read/write access||Appends new data to the end of file.||Create new file.|
|b||binary open||Opens a file in binary mode (**Windows only**).||?||?|
fopen() returns pointer to opened file stream on success, otherwise a
NULL pointer on fail.
You have to be careful when using
fopen() on a system with multiple threads, there is the possibility of creating race conditions.