cs24-23fa fopen

Introduction to Computing Systems (Fall 2023)

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.

Example

/* An implementation of the UNIX command `wc -l`,
 * which counts the number of lines in a file */

#include <stdio.h>

int main(int argc, char **argv) {
    if (argc != 2) {
        fprintf(stderr, "USAGE: %s <filename>\n", argv[0]);
        return 1;
    }

    // Try to open the file
    FILE *file = fopen(argv[1], "r");
    if (file == NULL) {
        /* Could not open file, so print out the error message,
         * e.g. `Failed to open nonexistent.txt: No such file or directory` */
        fprintf(stderr, "Failed to open %s: ", argv[1]);
        perror(NULL);
        return 1;
    }

    // Read one character at a time and count how many are newlines
    size_t newlines = 0;
    char c;
    while (fread(&c, sizeof(char), 1, file) > 0) {
        if (c == '\n') {
            newlines++;
        }
    }
    fclose(file);

    // Print out the number of newlines and the filename
    printf("%zu %s\n", newlines, argv[1]);
}

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()