← All languages
C function of the day
Random

fopen

Open a file and return a file stream pointer.

Description

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>.

Arguments

NameDescriptionOptional
filename Path to the file to open. No
mode String specifying the file access mode. No

Example

FILE *fp = fopen("data.txt", "r");
if (fp == NULL) {
    perror("Error opening file");
}