If file is opened using fopen() and in different mode then is it necessary to close it number of time or it can be closed once at end of code ?
Is it necessary to close a file number of time it is opened in program?
132 Views Asked by ameyCU At
3
There are 3 best solutions below
1

Each time you open the file, you are going to receive different file descriptors or file handles. So you have to close each file handle using fclose()
if opened via fopen()
or close()
if opened via open()
.
2

You have to close all of them.
When you use open
-family syscalls, they return you a file-descriptor
(fopen
returns FILE*
which is basically a struct that containts the file descriptor. Have a look on the FILE definition).
typedef struct
{
short level ;
short token ;
short bsize ;
char fd ; <-- here
unsigned flags ;
unsigned char hold ;
unsigned char *buffer ;
unsigned char * curp ;
unsigned istemp;
}FILE ;
As a result fopen()
will you give you two different FILE* (and different file-descriptors obviously) that you should close()/fclose()
finally.
The
open
function is the underlying primitive for thefopen
andfreopen
functions, that create streams.which creates and returns a new file descriptor for the file named by
filename
. The argumentmode
is used only when a file is created, but it doesn’t hurt to supply the argument in any case.So whenever an
open
orfopen
called a new file descriptor is created and these descriptors stay allocated until the program ends.The function
close
orfclose
closes the file descriptor fields. Closing a file has the following consequences:If you
open
orfopen
and don'tclose
, then that descriptor won't be cleaned up, and will persist until the program closes.The problem will be severe if there are a lots of calls of
open
or any file can potentially be opened multiple times (without closing each time), then the descriptors will be leaked, until the OS either refuses or unable to create another descriptor, in which case the call tofopen
fails and program can crash.On most POSIX operating systems, including Linux and Os X, each process is allocated a fixed table of file handles, or file descriptors. This is typically about 1024 handles. When you try to open 1025th file descriptor the operating system kills your process.
The problem is almost certainly that you are leaking file handles. That is, handles are being opened, and after you are done with them they are not closed.
To avoid the descriptor leak, you must need to
close
orfclose
before a file is reopened each time.Take a look what GNU described about Opening and Closing Files.