File code checks whether fopen succeeded before using the stream.

open failure `fopen` returns `0` when it cannot open the requested file.
guarded use Only pass a stream to I/O functions after checking that it is not `0`.

Error Checks

createFile
error_checks.c
Replay: real traced execution (multi-file project)
#include <stdio.h>

int main(void) {
    int createFile = 1;
    const char *path = "error_checks_demo.txt";

    if (createFile) {
        FILE *created = fopen(path, "w");
        if (created != 0) {
            fputs("ok\n", created);
            fclose(created);
        }
    }

    FILE *file = fopen(path, "r");
    int opened = (file != 0);

    if (file != 0) {
        fclose(file);
        remove(path);
    }

    printf("opened=%d\n", opened);
    return 0;
}
#include <stdio.h>

int main(void) {
    int createFile = 0;
    const char *path = "error_checks_demo.txt";

    if (createFile) {
        FILE *created = fopen(path, "w");
        if (created != 0) {
            fputs("ok\n", created);
            fclose(created);
        }
    }

    FILE *file = fopen(path, "r");
    int opened = (file != 0);

    if (file != 0) {
        fclose(file);
        remove(path);
    }

    printf("opened=%d\n", opened);
    return 0;
}
  1. createFile ← 1, path ← error_checks_demo.txt

    3int main(void) {4    int createFile→ 1 = 1; //@createFile=05    const char *path→ error_checks_demo.txt = "error_checks_demo.txt";
  2. created ← ⟨addr A⟩

    7if (createFile1) {8    FILE *created→ ⟨addr A⟩ = fopen(patherror_checks_demo.txt, "w");9    if (created != 0) {
  3. if (created != 0)

    8FILE *created = fopen(path, "w");9if (created⟨addr A⟩ != 0) {10    fputs("ok\n", created⟨addr A⟩);11    fclose(created⟨addr A⟩);12}
  4. file ← ⟨addr A⟩, opened ← 1

    15FILE *file→ ⟨addr A⟩ = fopen(patherror_checks_demo.txt, "r");16int opened→ 1 = (file⟨addr A⟩ != 0);
  5. if (file != 0)

    18if (file⟨addr A⟩ != 0) {19    fclose(file⟨addr A⟩);20    remove(patherror_checks_demo.txt);21}
  6. printf("opened=%d ", opened);

    23    printf("opened=%d\n", opened1);24    return 0;25}
    outputopened=1
  1. createFile ← 0, path ← error_checks_demo.txt, file ← 0, opened ← 0

    3int main(void) {4    int createFile→ 0 = 0;5    const char *path→ error_checks_demo.txt = "error_checks_demo.txt";67    if (createFile) {8        FILE *created = fopen(path, "w");9        if (created != 0) {10            fputs("ok\n", created);11            fclose(created);12        }13    }1415    FILE *file→ 0 = fopen(patherror_checks_demo.txt, "r");16    int opened→ 0 = (file0 != 0);1718    if (file != 0) {19        fclose(file);20        remove(path);21    }2223    printf("opened=%d\n", opened0);24    return 0;25}
    outputopened=0

Exercise: error_checks.c

Handle a failed file open without calling I/O functions on a null stream