Open a file and return a file stream pointer.
The fopen() function opens the file whose name is given by the string filename and associates a stream with it. The mode string specifies the type of access requested.
Common modes include "r" for reading, "w" for writing (truncates the file), "a" for appending, "rb" for reading in binary mode, and "w+" for reading and writing. If the file cannot be opened, fopen() returns NULL.
The returned FILE pointer is used in subsequent I/O operations such as fread(), fwrite(), fprintf(), and fscanf(). The file must be closed with fclose() when no longer needed. It is declared in <stdio.h>.
| Name | Description | Optional |
|---|---|---|
filename |
Path to the file to open. | No |
mode |
String specifying the file access mode. | No |
FILE *fp = fopen("data.txt", "r");
if (fp == NULL) {
perror("Error opening file");
}