gpt4 book ai didi

c - 在退出时关闭文件描述符是一种好习惯吗

转载 作者:太空狗 更新时间:2023-10-29 16:26:00 26 4
gpt4 key购买 nike

如果由于某种原因,我发现我的程序出现致命情况,我想退出并返回一个错误代码。有时, fatal error 的上下文超出了其他文件描述符的范围。关闭这些文件描述符是一种好习惯吗?据我所知,这些文件会在进程结束时自动关闭。

最佳答案

文件会自动关闭,但这是一个好习惯。

请参阅此示例中的 valgrind

david@debian:~$ cat demo.c
#include <stdio.h>

int main(void)
{
FILE *f;

f = fopen("demo.c", "r");
return 0;
}
david@debian:~$ valgrind ./demo
==3959== Memcheck, a memory error detector
==3959== Copyright (C) 2002-2010, and GNU GPL'd, by Julian Seward et al.
==3959== Using Valgrind-3.6.0.SVN-Debian and LibVEX; rerun with -h for copyright info
==3959== Command: ./demo
==3959==
==3959==
==3959== HEAP SUMMARY:
==3959== in use at exit: 568 bytes in 1 blocks
==3959== total heap usage: 1 allocs, 0 frees, 568 bytes allocated
==3959==
==3959== LEAK SUMMARY:
==3959== definitely lost: 0 bytes in 0 blocks
==3959== indirectly lost: 0 bytes in 0 blocks
==3959== possibly lost: 0 bytes in 0 blocks
==3959== still reachable: 568 bytes in 1 blocks
==3959== suppressed: 0 bytes in 0 blocks
==3959== Rerun with --leak-check=full to see details of leaked memory
==3959==
==3959== For counts of detected and suppressed errors, rerun with: -v
==3959== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 4 from 4)

如您所见,它引发了内存泄漏

在某些情况下,您可以使用 atexit():

#include <stdio.h>
#include <stdlib.h>

static FILE *f;

static void free_all(void)
{
fclose(f);
}

static int check(void)
{
return 0;
}

int main(void)
{
atexit(free_all);
f = fopen("demo.c", "r");
if (!check()) exit(EXIT_FAILURE);
/* more code */
return 0;
}

关于c - 在退出时关闭文件描述符是一种好习惯吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15246833/

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