Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What happens if you exit a program without doing fclose()?

Tags:

file

exit

fopen

Question:

What happens if I exit program without closing files?

Are there some bad things happening (e.g. some OS level file descriptor array is not freed up..?)

And to the answer the same in both cases

  • programmed exiting
  • unexpected crash

Code examples:

With programmed exiting I mean something like this:

int main(){
    fopen("foo.txt","r");
    exit(1);
}

With unexpected crash I mean something like this:

int main(){
    int * ptr=NULL;
    fopen("foo.txt","r");
    ptr[0]=0;  // causes segmentation fault to occur
}

P.S.

If the answer is programming language dependent then I would like to know about C and C++.

If the answer is OS dependent then I am interested in Linux and Windows behaviour.

like image 590
mks Avatar asked Sep 10 '11 07:09

mks


People also ask

What happens if you don't fclose ()?

As long as your program is running, if you keep opening files without closing them, the most likely result is that you will run out of file descriptors/handles available for your process, and attempting to open more files will fail eventually.

Does Fclose call close?

The fclose() function performs a close() on the file descriptor that is associated with the stream pointed to by stream. After the call to fclose(), any use of stream causes undefined behavior. Upon calling exit(), fclose() is performed automatically for all open files.

What happens if you don't close a file in C++?

In a large program, which runs on long after you have finished reading/writing to the file, not closing it means that your program is still holding the resource. This means that other processes cannot acquire that file until your program terminates (which may not be what you wish for). Arshia You are missing the point.

Why it is necessary to close a file in C?

A file needs to be closed after a read or write operation to release the memory allocated by the program. In C, a file is closed using the fclose() function. This returns 0 on success and EOF in the case of a failure.

Does exit close files?

Although exit() closes the file, the program has no way of determining if an error occurs while flushing or closing the file.


1 Answers

It depends on how you exit. Under controlled circumstances (via exit() or a return from main()), the data in the (output) buffers will be flushed and the files closed in an orderly manner. Other resources that the process had will also be released.

If your program crashes out of control, or if it calls one of the alternative _exit() or _Exit() functions, then the system will still clean up (close) open file descriptors and release other resources, but the buffers won't be flushed, etc.

like image 163
Jonathan Leffler Avatar answered Sep 28 '22 06:09

Jonathan Leffler