To make the question more clear:
[case 1]
#include <stdio.h>
int main () {
FILE* file = fopen("myfile.txt", "r");
return 0;
}
[case 2]
#include <stdio.h>
int main () {
int fd = open("myfile.txt", O_RDONLY);
return 0;
}
What happens when the file is not properly closed on both examples? Are the buffers flushed into the files? I am assuming the files will at least be closed automatically… is that right?
fopenis a C library function. It is unspecified how it is implemented. [Correction:] If you return frommain, all open file streams are closed for you (e.g. C11 7.21.3/5), but this need not happen if the program exits in other ways (e.g. via signal, such as viaabort).Your underlying OS implementation will of course clean up everything properly when a process terminates, but that’s only in as far as the global state of your system is concerned (e.g. all virtual memory associated to your process will be released, and all file descriptors closed, etc.). If the C library implements its own write buffer, say, then there’s no reason that that would automagically get flushed in every situation (though normal exit by returning from
mainis fine).That also addresses your case 2: If you use OS features directly, like the Posix
opencall, then you are indeed assured that those file descriptors will be closed when your process exits.