Once a file has been closed, its corresponding FILE*
typed variable becomes invalid and the stream may no longer be accessed through
this variable. In particular, a pointer to a FILE
object may not be passed to fclose
more than once.
Using the value of a pointer to a FILE
object after the associated file is closed results in undefined behavior.
#include <stdio.h>
#include <stdlib.h>
int process_file(int print) {
FILE *f = fopen("example.txt", "r");
if (!f) {
perror("fopen() failed");
return 1;
}
if (print) {
char buffer[256];
while (fgets(buffer, 256, f)) {
printf("%s", buffer);
}
fclose(f);
}
// Further processing ...
fclose(f); // Noncompliant: file associated with `f` might already be closed.
return 0;
}