What happens if I don’t call fclose() in a C program?

As long as your program is running, if you keep opening files without closing them, the most likely result is that you will run out of file descriptors/handles available for your process, and attempting to open more files will fail eventually. On Windows, this can also prevent other processes from opening or deleting the files you have open, since by default, files are opened in an exclusive sharing mode that prevents other processes from opening them.

Once your program exits, the operating system will clean up after you. It will close any files you left open when it terminates your process, and perform any other cleanup that is necessary (e.g. if a file was marked delete-on-close, it will delete the file then; note that that sort of thing is platform-specific).

However, another issue to be careful of is buffered data. Most file streams buffer data in memory before writing it out to disk. If you’re using FILE* streams from the stdio library, then there are two possibilities:

  1. Your program exited normally, either by calling the exit(3) function, or by returning from main (which implicitly calls exit(3)).
  2. Your program exited abnormally; this can be via calling abort(3) or _Exit(3), dying from a signal/exception, etc.

If your program exited normally, the C runtime will take care of flushing any buffered streams that were open. So, if you had buffered data written to a FILE* that wasn’t flushed, it will be flushed on normal exit.

Conversely, if your program exited abnormally, any buffered data will not be flushed. The OS just says “oh dear me, you left a file descriptor open, I better close that for you” when the process terminates; it has no idea there’s some random data lying somewhere in memory that the program intended to write to disk but did not. So be careful about that.

Leave a Comment