Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 719
Shen Avatar asked Jun 19 '12 06:06

Shen


People also ask

What is the purpose of using close () on a file you have written to?

Description. Python file method close() closes the opened file. A closed file cannot be read or written any more. Any operation, which requires that the file be opened will raise a ValueError after the file has been closed.

Why it is mandatory to close a file after use in Python?

You've learned why it's important to close files in Python. Because files are limited resources managed by the operating system, making sure files are closed after use will protect against hard-to-debug issues like running out of file handles or experiencing corrupted data.

What function is needed to close a file?

Closing a file is performed using the fclose() function. fclose(fptr);

What does close () do in C?

The close() function shall deallocate the file descriptor indicated by fildes. To deallocate means to make the file descriptor available for return by subsequent calls to open() or other functions that allocate file descriptors.


2 Answers

  • 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)

like image 92
John3136 Avatar answered Sep 28 '22 19:09

John3136


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.

like image 30
verisimilitude Avatar answered Sep 28 '22 20:09

verisimilitude