The fopen()
function is used to open a file, and the mode parameter specifies how the file should be opened. Below are the common modes available for fopen()
:
Mode | Description |
---|---|
r |
Opens the file for reading. The file must already exist; otherwise, fopen() returns NULL . |
w |
Opens the file for writing. If the file exists, it is overwritten. If the file does not exist, it is created. |
a |
Opens the file for appending. If the file does not exist, it is created. Data is always added to the end of the file. |
r+ |
Opens the file for both reading and writing. The file must already exist; otherwise, fopen() returns NULL . The file is not truncated. |
w+ |
Opens the file for both writing and reading. If the file exists, it is overwritten. If the file does not exist, it is created. |
a+ |
Opens the file for both appending and reading. If the file does not exist, it is created. Data is always added to the end of the file, but you can also read from the file. |
These are the same modes as above but allow handling of binary data, such as images or compiled files. They are indicated by adding a b
to the mode string:
Mode | Description |
---|---|
rb |
Read-only binary mode. |
wb |
Write-only binary mode. Creates or overwrites the file. |
ab |
Append-only binary mode. Creates the file if it doesn't exist. |
r+b or rb+ |
Read and write binary mode. The file must exist. |
w+b or wb+ |
Write and read binary mode. Creates or overwrites the file. |
a+b or ab+ |
Append and read binary mode. Creates the file if it doesn't exist. |
#include <stdio.h>
int main() {
FILE *file;
// Open for reading (file must exist)
file = fopen("example.txt", "r");
// Open for writing (creates if not exists, overwrites if exists)
file = fopen("example.txt", "w");
// Open for appending (creates if not exists)
file = fopen("example.txt", "a");
return 0;
}