← File I/O and Standard LibraryC PROGRAMMING 1.5.A

File I/O Basics

fopen/fclose and file modes.

StatusCollected
NotesChapter test: 4/5

Opening and closing a file, and the mode strings that decide what's actually allowed once it's open.

FILE *f = fopen("data.txt", "r");
if (f == NULL) {
    perror("fopen");
    return -1;
}

/* ... use f ... */

fclose(f);
ModeMeaning
"r"read, file must already exist
"w"write, creates the file or truncates it if it already exists
"a"append, creates the file if needed, writes go to the end
"rb" / "wb"same as r/w but binary mode — matters on some platforms for newline translation

fopen returns NULL on failure instead of throwing anything — a missing file, a permissions problem, a full disk all just come back as NULL, which is exactly why it gets checked before the pointer is used for anything.

Notes from readers

Comments — via GitHub