mahmood
mahmood

Reputation: 24665

Checking file handler before calling fclose

How can I check that when a fclose( fHandler ) is called, there was a fHandler = fopen(foo, "w"); prior to that? In a program there is a section that opens a file with increasing index number:

 char buffer[1024];
 sprintf(buffer, "./trace%d.txt", id);
 fHandler = fopen(buffer, "w");

and somewhere else in the code, I try to close such files.

 fclose(fHandler);

I want to check something like if (fHandle_is_still_open) prior to fclose(). It seems that checking fHandler with NULL works for the existence of file which is not whant I want. How can I fix that?

UPDATE:

The reason is that, somewhere in the execution, I get this error:

free(): invalid pointer

and gdb reports:

#0  __GI_raise (sig=sig@entry=6) at ../sysdeps/unix/sysv/linux/raise.c:50
#1  0x00007ffff5e34859 in __GI_abort () at abort.c:79
#2  0x00007ffff5e9f3ee in __libc_message (action=action@entry=do_abort, fmt=fmt@entry=0x7ffff5fc9285 "%s\n")
    at ../sysdeps/posix/libc_fatal.c:155
#3  0x00007ffff5ea747c in malloc_printerr (str=str@entry=0x7ffff5fc74ae "free(): invalid pointer")
    at malloc.c:5347
#4  0x00007ffff5ea8cac in _int_free (av=<optimized out>, p=<optimized out>, have_lock=0) at malloc.c:4173
#5  0x00007ffff5e94043 in _IO_deallocate_file (fp=0x555556ade8a0) at libioP.h:863
#6  _IO_new_fclose (fp=0x555556ade8a0) at iofclose.c:74

#7 is the fclose call.

Upvotes: 1

Views: 260

Answers (1)

anton-tchekov
anton-tchekov

Reputation: 1098

There is no way to check if a FILE* was already closed. The safest way is to check if fHandler is NULL, then set the fHandler to NULL directly after you call fclose.

if(fhandler)
{
    fclose(fHandler);
    fHandler = NULL;
}

Upvotes: 5

Related Questions