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 ?
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()
.
The open
function is the underlying primitive for the fopen
and freopen
functions, that create streams.
int open (const char *filename, int flags[, mode_t mode])
which creates and returns a new file descriptor for the file named by filename
. The argument mode
is used only when a file is created, but it doesn’t hurt to supply the argument in any case.
So whenever an open
or fopen
called a new file descriptor is created and these descriptors stay allocated until the program ends.
The function close
or fclose
closes the file descriptor fields. Closing a file has the following consequences:
If you open
or fopen
and don't close
, 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 to fopen
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
or fclose
before a file is reopened each time.
Take a look what GNU described about Opening and Closing Files.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With