C <stdio.h> - fopen() Function
The C <stdio.h> fopen() function opens a file indicated by filename and returns a file stream associated with that file. The mode is used to determine the file access mode.
The file stream can be disassociated from the file by calling fclose() or freopen() function. All opened files are automatically closed on normal program termination.
Syntax
FILE * fopen ( const char * filename, const char * mode );
Parameters
filename |
Specify file name to associate the file stream to. It can include a path (if supported by the system). |
mode |
Specify C string containing a file access mode. See the table below for more details. |
Modes | Description | Action: If file exists | Action: If file does not exist |
---|---|---|---|
"r" | Read: open a file for reading | Read from start | Failure to open |
"w" | Write: create a file for writing | Delete contents | Create new |
"a" | Append: append to a file | Write to end | Create new |
"r+" | Read extended: open a file for read/write | Read from start | Error |
"w+" | Write extended: create a file for read/write | Delete contents | Create new |
"a+" | Append extended: open a file for read/write | Write to end | Create new |
- The above discussed mode specifiers opens a file as a text file. To open a file as a binary file, a "b" character has to be included in the mode string. This additional "b" character can either be appended at the end of the string ("rb", "wb", "ab" OR "r+b", "w+b", "a+b") or be inserted between the letter and the "+" sign for the mixed modes ("rb+", "wb+", "ab+").
- File access mode flag "x" can optionally be appended to "w" or "w+" specifiers. This flag forces the function to fail if the file exists, instead of overwriting it (since C2011).
- The behavior is undefined if the mode is not one of the strings listed above. Some implementations define additional supported modes.
Return Value
On success, returns a pointer to a FILE object that can be used to identify the stream on future operations. On error, returns a null pointer. On most library implementations, the errno variable is also set to a system-specific error code on failure.
Example:
Lets assume that we have a file called test.txt. This file contains following content:
This is a test file. It contains dummy content.
In the example below, file is opened using fopen() to read the content of the file.
#include <stdio.h> int main (){ //open the file in read mode FILE *pFile = fopen("test.txt", "r"); //first character in the file int c = getc(pFile); //if first character is not EOF, reads and writes //characters from the file until EOF is reached while (c != EOF) { putchar(c); c = getc(pFile); } //close the file fclose(pFile); return 0; }
The output of the above code will be:
This is a test file. It contains dummy content.
❮ C <stdio.h> Library