What happens to FILE pointer after file is closed?

2019-01-14 23:43发布

问题:

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?

回答1:

Since arguments are passed by value there is not way fclose could set your file pointer to NULL. Since fclose probably destroys the FILE you have to

  • Manually set the file pointer to NULL after doing a fclose (won't work if you close it in a different function unles you use FILE **)
  • Don't end up in a situation where you "forget" whether you closed it or not (might be tricky)


回答2:

Peter Norvig quotes Auguste Comte (1798-1857):

  "Nothing is destroyed until it is replaced"

You could use the macro:

  #define fclose(fp)  ((fp) ? fclose(fp) : 0, (fp) = 0)

This fixes two different and opposing problems:

  • The FILE * pointer is NULL'd after fclose, so it can't be fclose'd twice.

  • This version of fclose will accept a NULL argument. Many common versions of fclose--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 it FCLOSE, to follow convention.



回答3:

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

int a malloc(10);
free(a);

still a will not be NULL

in most case i always do this things

free(a);
a=NULL;

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 ..



回答4:

Yes you can do this. and better way is to set fp to NULL else

it will be dangling pointer (a pointer which is pointing to something which it does not own or which does not exist)



标签: c file fclose