C/C++ Arena

Step 3 of 7

When fopen fails

Files go missing, permissions get denied and disks fill up. fopen returns NULL when it fails, and every professional C program checks it:

FILE *f = fopen(path, "r");
if (f == NULL) {
    perror(path);     // prints e.g. "config.txt: No such file or directory" to stderr
    return -1;
}

A function that opens a file should also close it on every path out of the function, including early returns after errors.

Your turn: write long count_lines(const char *path) that returns the number of '\n' characters in the file, or -1 if it can't be opened. Read with fgetc, which returns one character at a time, or EOF at the end.

Previous: Reading lines with fgets Next: Loading records