在退出時關閉檔案描述符是一個很好的做法
如果由於某種原因,我發現我的程式中有一個致命的情況,我想退出一個錯誤程式碼.
有時,致命錯誤的上下文不在其他檔案描述符的範圍之內.
關閉這些檔案描述符是一個很好的做法.
據我所知,這些檔案在程序宕機時自動關閉.
檔案自動關閉,但這是一個很好的做法.
在這個例子上見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; }
http://stackoverflow.com/questions/15246833/is-it-a-good-practice-to-close-file-descriptors-on-exit