I have opened a file
FILE *fp = fopen("file.txt","r");
fclose(fp);
scenario is that I forgot to assign null to fp
Now I want to check whether this file is open or not using same fp
pointer
I have opened a file
FILE *fp = fopen("file.txt","r");
fclose(fp);
scenario is that I forgot to assign null to fp
Now I want to check whether this file is open or not using same fp
pointer
You can't. The value of fp
after closing it is indeterminate: http://www.iso-9899.info/n1256.html#7.19.3p4
This means any operation on it results in undefined behaviour.
this might help --->
if(fp == NULL)
printf("Error in file opening\n")
Using fopen() returned pointer after closing it is indeterminate.
Instead if you use open() system call you can access using the fd to check if it open or not in /proc folder
/proc contains all the details regarding the process. you can access the current process using /proc/self inside which is a file fd /proc/self/fd each file in there is named after a fd.
(Use g_dir_open, g_dir_read_name and g_dir_close to do the listing)
If file not open then fopen
return null to fp
. Null check after fopen()
. Assign NULL after fclose
.
In your case you can check file open or not by checking fp
to NULL.
FILE *fp = fopen("file.txt","r");
if (fp == NULL) {
printf("not open\n");
return -1 ;
}
else
printf("File open\n");
if(fp != NULL) {
fclose(fp);
fp = NULL;
}
Upon successful completion fopen(), fdopen() and freopen() return a FILE pointer. Otherwise, NULL is returned and errno is set to indicate the error.