gpt4 book ai didi

c - fclose 似乎不能在 C 中工作

转载 作者:太空宇宙 更新时间:2023-11-04 03:58:19 24 4
gpt4 key购买 nike

    FILE *file = fopen(argv[1], "r");
if(file != NULL){
char command[MAX_BUFFER];
while(fgets(command, MAX_BUFFER, file) != NULL){ //read line
//operations
}
fclose(file);
}
else write(fileno(stderr), ERROR_MESSAGE, strlen(ERROR_MESSAGE));

我正在研究一个非常基本的 UNIX shell 实现,它从文件中逐行读取和执行。从上面的代码中,我试图找出为什么 fclose() 可能会失败,因为 valgrind 似乎告诉我我已经打开了这个文件描述符。

我假设泄漏摘要中“仍可访问”的 568 字节是指以某种方式失败的 fclose() 是否正确?

==25428== FILE DESCRIPTORS: 4 open at exit.
==25428== Open file descriptor 3: test
==25428== at 0x4F186B0: __open_nocancel (syscall-template.S:82)
==25428== by 0x4EAC628: _IO_file_fopen@@GLIBC_2.2.5 (fileops.c:233)
==25428== by 0x4EA1265: __fopen_internal (iofopen.c:93)
==25428== by 0x400C0C: main (in /home/Desktop/sh)
==25428==
==25428== Open file descriptor 2: /dev/pts/0
==25428== <inherited from parent>
==25428==
==25428== Open file descriptor 1: /dev/pts/0
==25428== <inherited from parent>
==25428==
==25428== Open file descriptor 0: /dev/pts/0
==25428== <inherited from parent>
==25428==
==25428== LEAK SUMMARY:
==25428== definitely lost: 0 bytes in 0 blocks
==25428== indirectly lost: 0 bytes in 0 blocks
==25428== possibly lost: 0 bytes in 0 blocks
==25428== still reachable: 568 bytes in 1 blocks
==25428== suppressed: 0 bytes in 0 blocks

最佳答案

对了,检查返回值,也贴一个perror来得到一个简短的解释。如果您想确认它仍然打开,请尝试 lsof,但您可能需要用 grep 获取程序名称或 pid,因为可能有几十个。

关于c - fclose 似乎不能在 C 中工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14392540/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com