Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What happens to FILE pointer after file is closed?

Tags:

c

file

fclose

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?

like image 576
CuriousCoder Avatar asked Dec 09 '11 04:12

CuriousCoder


2 Answers

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)
like image 75
cnicutar Avatar answered Oct 17 '22 05:10

cnicutar


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

like image 29
Jeegar Patel Avatar answered Oct 17 '22 04:10

Jeegar Patel