Link to home
Start Free TrialLog in
Avatar of librazone
librazone

asked on

Using fclose

Are there any serious problems caused by failing to use fclose at the end of a file processing operation?thanks
Avatar of RajeshTN
RajeshTN

The resources of the process - Files, memory, Device locks will be freed when the process dies. But it is a good and a safe practice to close all files after they've been used. There would be more scopes for bugs if u keep files open when u dont want to use them any more. Say for example u have opened a file as
FILE *fp1=fopen("temp.txt","w");
.....
FILE * fp2=fopen("temp.txt","w");
.......


The program would obviously bomb somewhere since u write to the same file using 2 pointers.
Also:

FILE *fp1=fopen("temp.txt","w");
...
fp1=fopen("temp1.txt","w");
...

In this example, the buffer allocated initially for fp1 would not be freed and the memory consumption of ur program would unnecessarily increase.

-Rajesh



another problem can be that .. if u want to open lots of file in the program process them and then close them.. and it is supposed to run continuously for long hours(most probably a server/daemon) . then after some time the number of open file handles will exceed the upper limit and u wont be able to open further files ..
say u r implementing a ftp server / or some webserver .. then every time a file is requested .. u open the file read it and send to the client .. but if u "forget" to close them after processing .. then after some time u wont be able to open further files ..
and which is very critical conditon for a server like this..
ASKER CERTIFIED SOLUTION
Avatar of gj62
gj62

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Of course, you should close those files when you no longer need the pointer, for all the reasons mentioned above...