CS 3 (Spring 2024) fopen

Name

fopen - open a file stream

Synopsis

#include <stdio.h>

FILE *fopen(const char *file_path, const char *mode);

Description

The fopen() function creates a file stream for the file at the path specified by file_path. A file stream (represented by the FILE type) keeps track of its current position in the file, which is updated by fread(), fwrite(), and fseek(). The argument mode determines how the file is opened, and should be one of the following strings:

r
Open for reading. The stream is positioned at the beginning of the file.
r+
Open for reading and writing. The stream is positioned at the beginning of the file.
w
Open for writing. If the file already exists, it is emptied; otherwise, an empty file is created. The stream is positioned at the beginning of the file.
w+
Open for reading and writing. If the file already exists, it is emptied; otherwise, an empty file is created. The stream is positioned at the beginning of the file.
a
Open for appending. The file is created if it does not exist. All writes occur at the end of the file, regardless of the current position.
a+
Open for reading and appending. The file is created if it does not exist. The stream is positioned at the beginning of the file for reading, but all writes occur at the end of the file.

Return Value

Upon successful completion, fopen() returns a non-NULL FILE pointer. Otherwise, NULL is returned and errno is set to indicate the error.

Errors

EINVAL
The mode provided was invalid.

fopen() may also fail and set errno for any of the errors specified for malloc() or the open() syscall.

See Also

fclose(), fread(), fwrite(), fflush(), fseek()