Why do I have to use close() to close a file?

10,054

Solution 1

  • If the file has any sort of buffering behind it it and you don't call close then you could potentially lose data.

  • If the OS has limited resources (e.g. number of open files) then by not closing files you are wasting system resources.

  • Using a descriptor once the file is closed is pointless at best, massive bug at worst (a bit like using memory after it has been freed)

Solution 2

The close() function closes the connection between the program and an open file identified by a handle. Any unwritten system buffers are flushed to the disk, and system resources used by the file are released

The bolded part is the prime reason why a file should be closed

Closing a file has the following consequences:

1)The file descriptor is deallocated.
2) Any record locks owned by the process on the file are unlocked.
3) When all file descriptors associated with a pipe or FIFO have been closed, any unread data is discarded.

Solution 3

If you don't close a file opened for reading it can be blocked for concurrent writes. If you don't close a file opened for writing - you can loose a piece of last-written data which OS holds in the buffer.

And never use a descriptor of already closed file. This has no sense.

Share:
10,054
Shen
Author by

Shen

Updated on July 31, 2022

Comments

  • Shen
    Shen almost 2 years

    I'm learning some file functions and hence have a doubt.

    I'm curious about why it is necessary to call close() to close a file? If I did not call close() after reading/writing a file, what things might happen? And if I did call close(),can I still use the file descriptor?