Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is fclose needed when fopen has failed?

Tags:

c++

c

consider the below code snippet.

{
....
FILE *fptr = fopen("file_that_does_not_exist","r");
...
}

here, if fopen fails, do we still need to call fclose() for some cleanup ??

like image 496
ango Avatar asked Feb 15 '11 13:02

ango


People also ask

What happens if I don't use 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.

What happens when fopen fails?

"fopen" opens a file for subsequent reading or writing. If successful, "fopen" returns a pointer-to-structure; if it fails, it returns NULL.

Why is Fclose important?

Calling fclose will ensure the file descriptor is properly disposed of and output buffers flushed so the data written to the file will be present in the file on disk.

What is the difference between fopen () and fclose ()?

The fopen() function is used to open the file or an URL. The fclose() function closes the opened file.


1 Answers

No, since fopen() returns 0, which is an invalid file handle. fclose() may even crash if you try to do this.

like image 160
moatPylon Avatar answered Oct 07 '22 19:10

moatPylon