13.3. fclose()

The opposite of fopen()--closes a file when you're done with it so that it frees system resources.


#include <stdio.h>

int fclose(FILE *stream);


When you open a file, the system sets aside some resources to maintain information about that open file. Usually it can only open so many files at once. In any case, the Right Thing to do is to close your files when you're done using them so that the system resources are freed.

Also, you might not find that all the information that you've written to the file has actually been written to disk until the file is closed. (You can force this with a call to fflush().)

When your program exits normally, it closes all open files for you. Lots of times, though, you'll have a long-running program, and it'd be better to close the files before then. In any case, not closing a file you've opened makes you look bad. So, remember to fclose() your file when you're done with it!

Return Value

On success, 0 is returned. Typically no one checks for this. On error EOF is returned. Typically no one checks for this, either.


FILE *fp;

fp = fopen("spoonDB.dat", r"); // (you should error-check this)
fclose(fp);   // pretty simple, huh.

See Also