+ 2

File Handeling

What if dont close the file after opeaning or making it; What error/problem does it makes;

24th Nov 2022, 11:15 AM
Sunil Shrestha
Sunil Shrestha - avatar
5 ответов
+ 4
It might affect your sleep as you ponder whether you should have closed that file and now you are worrying about unknown bad things that could happen all because of a forgotten close(). There is a real problem with leaving a file open unnecessarily. In a multi-user environment it prevents others from opening the file for writing. The other sessions may hang until your program releases the write lock on the file by closing it. My story: I tracked down this issue when a program seemed to hang daily around lunch time. It turned out that the program opened a file and then prompted the user to answer a question. Well, sometimes a user would leave for lunch at that point and then nobody else could use their own copy of the program. All the other programs were hung waiting to write the same file until that person returned and answered the prompt! Lesson learned: don't prompt for input while writing a file. Simply open, write, close and nothing else.
25th Nov 2022, 3:24 PM
Brian
Brian - avatar
+ 2
It will be there in the memory until the program is terminated. Memory is limited, you know. So always close a file when you don't need it.
24th Nov 2022, 11:18 AM
Kashyap Kumar
Kashyap Kumar - avatar
+ 2
This can lead to memory leaks, which will eventually crash the operating system. Ever seen a BSoD? https://en.m.wikipedia.org/wiki/Blue_screen_of_death
24th Nov 2022, 11:33 AM
Tibor Santa
Tibor Santa - avatar
+ 1
Or it doesnt affect anything?
24th Nov 2022, 11:16 AM
Sunil Shrestha
Sunil Shrestha - avatar
0
as i know in c++ if you open a file with std::fstream and not close it, it will close when the fstream object destroyed. In C it will stay loaded in memory till your process close. In python I'm not sure but i think it is the same as C++
24th Nov 2022, 12:45 PM
Giannis
Giannis - avatar