closing a file\nunanswered · 82 seconds left\nwhy is it important to close a file when your code is done…

closing a file\nunanswered · 82 seconds left\nwhy is it important to close a file when your code is done with the file?\nselect all that apply\na\nto ensure all written data is flushed to the file (it is moved from the program to the file).\nb\nto limit the number of file handles a program has open (and ensure we dont run out of files the operating system will allow us to open).\nc\nwe cant open another file until we closed a previous file.\nd\nto ensure other programs can access the file if they need it.
Answer
Brief Explanations:
- Option A: When data is written to a file in code, it may be buffered (stored temporarily in memory). Closing the file ensures that all the buffered data is actually written (flushed) to the physical file. For example, in Python, if you write to a file object and don't close it, the data might not be saved immediately.
- Option B: Operating systems have a limit on the number of files a program can have open simultaneously (file handles). By closing files when done, the program stays within this limit. If too many files are left open, the program may encounter errors when trying to open new files.
- Option C: This is incorrect. In most operating systems and programming languages, you can open multiple files without closing previous ones (up to the system - imposed limit). For example, in a Python script, you can have multiple file objects open at the same time as long as the limit is not reached.
- Option D: When a file is open in a program (especially if it's open in a mode that locks the file, like exclusive write), other programs may be restricted from accessing it. Closing the file releases any locks (in non - locked modes, it still frees up the system resources associated with the file handle), allowing other programs to access the file if needed.
Answer:
A. To ensure all written data is flushed to the file (it is moved from the program to the file). B. To limit the number of file handles a program has open (and ensure we don't run out of files the operating system will allow us to open). D. To ensure other programs can access the file if they need it.