The following program was taken from Windows System Programming (Fourth Edition) by Johnson M. Hart:
#include<stdio.h>
#include<errno.h>
#define BUF_SIZE 256
int main(int argc, char *argv[])
{
FILE *inFile, *outFile;
size_t bytesIn, bytesOut;
char rec[BUF_SIZE];
if (argc != 3) {
printf("Syntax : scp source destination.\n");
return 1;
}
inFile = fopen(argv[1], "rb");
if (inFile == NULL) {
perror(argv[1]);
return 2;
}
outFile = fopen(argv[2], "wb");
if (outFile == NULL) {
perror(argv[2]);
//fclose(inFile);
return 3;
}
while ((bytesIn = fread(rec, 1, BUF_SIZE, inFile)) > 0) {
bytesOut = fwrite(rec, 1, bytesIn, outFile);
if (bytesIn != bytesOut) {
perror("Fatal write error.");
//fclose(inFile); fclose(outFile);
return 4;
}
}
fclose(inFile);
fclose(outFile);
return 0;
}
It works the same with or without closing the files in the commented lines.
However, after having read previous posts I am not sure what is the best practice.
Let OS do its job or close them whenever I feel I should?
I am saying this because I have seen situations in windows GUI apps that, when I close the handles instead of the OS, I am causing a small glitch on the screen and I am essentially delaying the OS because I do the cleaning like many C++ books say.
I am not using anything windows here...it's a CRT implementation but still...
If the whole program ends after the fclose than it doesn't really make a difference. However, this usually isn't the case. You usually open a file write something into it and if you don't close it then you wont be able to reopen it nor will any other program be able to do so. Plus, if you just keep opening files then there will be a significant overhead at termination when the OS needs to close all of them. While, if you closed them when you no longer needed them then it would have evenly spread out over the course of time while the program was running.
Think of it as being in the library. If you take a bunch of books off the shelves and don't put them back, but than leave nothing really happens, because the librarian will put them back (although he will be occupied with it for quite some time). However, if you take a bunch of books and don't use them and you just keep piling them up on your desk and you don't leave for a long time, than for all those time the other guys in the library wont be able to use them.
The reason for using fclose even if your program does terminate is scalability, because if you don't and then you improve upon it, or use it as a function in an other program etc. then all those left out fcloses will come back to bite you in the ass. Plus, it is more secure as well, because if you closed it then it cannot be accidentally written or read. It might seem silly if you haven't worked in a professional environment where multiple people work on the same code but defensive programming is a VERY useful and essential tool.