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.
Lesson 07
Keep cleanup on every file I/O path so early returns and write failures do not leak file handles.
#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;
}#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;
}The good version keeps close logic on the same path as the write result. Both fputs and fclose can affect the final status.
The bad version returns before fclose when the write fails. That leaks the file handle and can also hide buffered write errors.