4

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

Ahmed Salman Tahir
  • 1,783
  • 1
  • 17
  • 26
Avinash Kumar
  • 739
  • 2
  • 10
  • 25
  • Ummm... don't forget to null out the pointer? – Ed S. Jan 30 '14 at 07:20
  • 3
    Do not try to hide the problem. Fix it correctly and do the NULL assignment after the `fclose`. – user694733 Jan 30 '14 at 07:22
  • Although, you can do what you're after – Ed S. Jan 30 '14 at 07:22
  • possible duplicate of [How to check if a given file descriptor stored in a variable is still valid?](http://stackoverflow.com/questions/12340695/how-to-check-if-a-given-file-descriptor-stored-in-a-variable-is-still-valid) – Ed S. Jan 30 '14 at 07:23
  • 1
    also the recommendation from the previous comment has a problem. If the pointer is not initialized, it might point to a valid file pointer (left over from a previous call as stack residue). – steve Jan 30 '14 at 07:26
  • 1
    Unfortunately, the stdio functions dereference the pointer, and expect it to point to a valid (though *logically* opaque) file stream structure. You have a dangling pointer, and there's no portable way to determine if it points to a valid object, or even addressable memory. – Brett Hale Jan 30 '14 at 07:29

4 Answers4

6

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.

Brave Sir Robin
  • 1,046
  • 6
  • 9
1

this might help --->

if(fp == NULL)
   printf("Error in file opening\n")
Ansh David
  • 654
  • 1
  • 10
  • 26
1

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)

KARTHIK BHAT
  • 1,410
  • 13
  • 23
0

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.

What happens to FILE pointer after file is closed?

Community
  • 1
  • 1
sujin
  • 2,813
  • 2
  • 21
  • 33