Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it necessary to close a file number of time it is opened in program?

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 ?

like image 835
ameyCU Avatar asked Feb 09 '23 17:02

ameyCU


2 Answers

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().

like image 127
Steephen Avatar answered May 07 '23 11:05

Steephen


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:

  • The file descriptor is de-allocated.
  • Any record locks owned by the process on the file are unlocked.
  • When all file descriptors associated with a pipe or FIFO have been closed, any unread data is discarded.

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.

like image 25
rakeb.mazharul Avatar answered May 07 '23 12:05

rakeb.mazharul