I wish to know what happens to FILE pointer after the file is closed. Will it be NULL?
Basically, I want to check if a file has already been closed before closing a file.
For example as follows:
FILE *f;
if(f!=NULL)
{
fclose(f);
}
Can I do this or is there any other way to go about it?
Since arguments are passed by value there is not way
fclose
could set your file pointer toNULL
. Sincefclose
probably destroys theFILE
you have toNULL
after doing afclose
(won't work if you close it in a different function unles you useFILE **
)Yes you can do this. and better way is to set
fp
toNULL
elseit will be dangling pointer (a pointer which is pointing to something which it does not own or which does not exist)
FILE * It's a pointer to a FILE structure, when you call fclose() it will destroy/free FILE structure but will not change the value of FILE* pointer means still it has the address of that FILE structure which is now not exits.
same things happem with any pointer getting with malloc
still a will not be NULL
in most case i always do this things
Edit: you can not check whether its CLOSED/freed at any time. just to make sure you can assign it NULL after free/fclose so you can check its NULL or not and go ahead ..
Peter Norvig quotes Auguste Comte (1798-1857):
You could use the macro:
This fixes two different and opposing problems:
The
FILE *
pointer is NULL'd afterfclose
, so it can't befclose'd
twice.This version of
fclose
will accept a NULL argument. Many common versions offclose
--such as those in HPUX, SGI, and CYGWIN--are happy with NULLs. It is odd that the FreeBSD-inspired versions such as in Linux, and Microsoft, aren't.Of course, the macro introduces its own problems:
It doesn't return the proper error value. But if you wanted to see this, you can disable the macro with extra parentheses, as in:
if ((fclose)(fp) == EOF){ /* handle error... */ }
It doesn't have function semantics, as it uses its argument multiple times. But it is hard to imagine this causing a problem. But you can use
(fclose)
. Or name itFCLOSE
, to follow convention.