Avinash Kumar
Avinash Kumar

Reputation: 787

How to check a file is opened or not if i forgot to assign null to file 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

Upvotes: 4

Views: 21812

Answers (4)

sujin
sujin

Reputation: 2853

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?

Upvotes: 0

KARTHIK BHAT
KARTHIK BHAT

Reputation: 1420

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)

Upvotes: 1

Ansh David
Ansh David

Reputation: 672

this might help --->

if(fp == NULL)
   printf("Error in file opening\n")

Upvotes: 1

Brave Sir Robin
Brave Sir Robin

Reputation: 1046

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.

Upvotes: 6

Related Questions