在调用 fclose 之前检查文件处理程序

mah*_*ood 1 c file

我如何检查当 a被调用时,之前fclose( fHandler )有 a ?fHandler = fopen(foo, "w");在程序中,有一个部分打开一个索引号递增的文件:

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

在代码的其他地方,我尝试关闭此类文件。

 fclose(fHandler);
Run Code Online (Sandbox Code Playgroud)

if (fHandle_is_still_open)我想检查一下之前的事情fclose()。似乎检查fHandler文件NULL是否存在,这不是我想要的。我该如何解决这个问题?

更新:

原因是,在执行过程中的某个地方,我收到此错误:

free(): invalid pointer
Run Code Online (Sandbox Code Playgroud)

和 gdb 报告:

#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
Run Code Online (Sandbox Code Playgroud)

#7 是 fclose 调用。

小智 5

无法检查 a 是否FILE*已经关闭。最安全的方法是检查是否fHandler为 NULL,然后fHandler在调用 fclose 后直接将其设置为 NULL。

if(fhandler)
{
    fclose(fHandler);
    fHandler = NULL;
}
Run Code Online (Sandbox Code Playgroud)

  • 当然,这需要首先将变量初始化为“NULL”。 (4认同)