C

Lesson 07

File I/O cleanup paths

Keep cleanup on every file I/O path so early returns and write failures do not leak file handles.

Good Code

src/review_file.c
#include <stdio.h>

int save_review(const char *path, const char *body)
{
    FILE *file = fopen(path, "w");
    if (file == NULL) {
        return -1;
    }

    // One cleanup exit closes the file on every failure path.
    int result = 0;
    if (fputs(body, file) == EOF) {
        result = -1;
    }
    if (fclose(file) == EOF) {
        result = -1;
    }

    return result;
}

Bad Code

review_file.c
#include <stdio.h>

int save_review(const char *path, const char *body)
{
    FILE *file = fopen(path, "w");
    if (file == NULL) {
        return -1;
    }

    if (fputs(body, file) == EOF) {
        // This early return leaves the file handle open.
        return -1;
    }

    fclose(file);
    return 0;
}

Review Notes

What to review

Good Code

The good version keeps close logic on the same path as the write result. Both fputs and fclose can affect the final status.

Bad Code

The bad version returns before fclose when the write fails. That leaks the file handle and can also hide buffered write errors.

Takeaways

  • File cleanup should be visible on success and failure paths, especially when the function can return before the bottom.