5

What happens if I do not close a file after writing to it?

Let us assume we got an too many open files error and due to that the program crashes.

Does the OS handle that for me? And if this damages the not-closed files, how do I notice that they are damaged?

Michael Dorner
  • 17,587
  • 13
  • 87
  • 117
  • The file becomes locked and you can't edit or modify it anyway, which I'd assume would mean that you can't delete it as well. And if you're creating these on the fly probably could run into a... you guessed it stack overflow. Or a huge memory leak and eventually crashing your app, PC, and/or Server. – Dylan Wright Aug 18 '17 at 17:51
  • Your computer could handle this if you could find the process and kill the process controlling it. – Dylan Wright Aug 18 '17 at 17:51
  • Possible duplicate ? https://stackoverflow.com/questions/8175827/what-happens-if-i-dont-call-fclose-in-a-c-program – Tony Tannous Aug 18 '17 at 17:52
  • Yes, if there are too many open (not closed) files, there is the `too many open files error`. But what happens to the files themselves? – Michael Dorner Aug 18 '17 at 17:52
  • Thanks @TonyTannous for sharing this, I saw that before. But this is specific to C and assumes that there is a proper exit. – Michael Dorner Aug 18 '17 at 17:53
  • Your question then is not clear. `file is damaged by not correctly closing it?` I would guess just like if you allocate memory and not free it... after termination the OS will take care of it. After process termination, the parent process has to perform a wait which will clean the process image. – Tony Tannous Aug 18 '17 at 17:56
  • @TonyTannous If that is the case ("after termination [...]") than that's exactly I wanted to know. :-) I would be happy if you post it as answer so I can mark it as the correct answer. Thanks for your help! – Michael Dorner Aug 18 '17 at 18:00

2 Answers2

3

From exit()

_exit() does close open file descriptors, and this may cause an unknown delay, waiting for pending output to finish.

Each return hides a system call to exit, so any unclosed descriptor is closed by the OS.

Tony Tannous
  • 14,154
  • 10
  • 50
  • 86
2

Generally speaking, if you write to a file, then your application crashes, the operating system will flush the buffers to the disk and clean up for you. The same will occur if your program exits without explicitly closing the files. This does not damage files.

The bad situation is when you write to a file and someone pulls the plug out on the computer.

user3344003
  • 20,574
  • 3
  • 26
  • 62