Question about fclose
Where should the fclose function go in this example:
Where should the fclose instruction go (the top or bottom one commented out)?
FileHandle = fopen(...);
if (FileHandle != 0)
Inside the if statement, although from what I'm reading from various references, if you pass NULL into fclose() nothing horrible will happen.
This may not be true for all functions that require you to pass a pointer. Know the details about the function you're calling and if passing a NULL pointer will cause issues.
Thanks. I wasn't quite sure on that. I thought that, if the file was opened, it had to be closed, even if the file couldn't be found (causing the handle to be zero). If the file didn't exist, it wouldn't then reach the fclose instruction causing a leak (or something like that).
fopen() returns NULL upon failure, which means that any FILE struct that it malloc()ed was free()ed before it returned.
If it wouldn't clean up after itself before returning NULL, then you would have a memory leak that you wouldn't be able to fix because there would be no way of knowing how to deallocate the memory it allocated. If it managed to open the file, but yet return NULL, you would have a similar problem, with no way of knowing how to close the file.
So this is why, when you receive NULL from fopen(), you can tell there's nothing for you to close and you can simply process the error.
In other news, FILE pointers (handles) or pointers in general don't always e-null-uate (is that a word, meh I like the way it sounds) to integer zero. Meaning:Is not garaunteed to catch a null pointer. What you want is:or if NULL isn't defined:
> fp == 0
> Is not garaunteed to catch a null pointer. What you want is:
Yes it is.