简体   繁体   中英

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.

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM