如何在 C 中正确关闭文件
How to properly close a file in C
我通常从 stdin
或文件名读取:
FILE *open_file(char *filename, FILE *fallback, char *mode)
{
FILE *fp = fallback;
if (filename != NULL) {
if ((fp = fopen(filename, mode)) == NULL) {
fprintf(stderr, "Error: cannot open '%s'!\n", filename);
exit(ERROR_CANNOT_READ_FILE);
}
}
if (fp == NULL) {
fprintf(stderr, "Error: file error!\n");
exit(ERROR_CANNOT_READ_FILE);
}
return fp;
}
int main(int argc, char* argv[]) {
FILE *fp = open_file(argc > 1 ? argv[1] : NULL, stdin, "r");
// some stuff...
if(!fclose(fp)) {
exit(EXIT_FAILURE);
}
}
在这个例子中,我可能对 fclose
有疑问。我无法关闭 stdin
和 stdout
。我怎样才能正确和有条件地关闭 fp
?
我必须关闭 fp
吗?
fclose() returns 0 如果文件成功关闭但在您的代码中
if(!fclose(fp)) {
exit(EXIT_FAILURE);
}
如果 fclose() 成功关闭文件 main() return EXIT_FAILURE,那么你可以将其更改为
if(fclose(fp)) {
exit(EXIT_FAILURE);
}
或
if(fclose(fp)!=0){
exit(EXIT_FAILURE);
}
编辑:
The question is more: must I close fp if it is not stdin or stdout?
if( (fp!=stdin) && (fp!=stdout) )
if( fclose(fp) )
exit(EXIT_FAILURE);
或
if( (fp!=stdin&&fp!=stdout) && fclose(fp) )
exit(EXIT_FAILURE);
因为 && 是 short-circuiting operator 并且保证从左到右求值
我通常从 stdin
或文件名读取:
FILE *open_file(char *filename, FILE *fallback, char *mode)
{
FILE *fp = fallback;
if (filename != NULL) {
if ((fp = fopen(filename, mode)) == NULL) {
fprintf(stderr, "Error: cannot open '%s'!\n", filename);
exit(ERROR_CANNOT_READ_FILE);
}
}
if (fp == NULL) {
fprintf(stderr, "Error: file error!\n");
exit(ERROR_CANNOT_READ_FILE);
}
return fp;
}
int main(int argc, char* argv[]) {
FILE *fp = open_file(argc > 1 ? argv[1] : NULL, stdin, "r");
// some stuff...
if(!fclose(fp)) {
exit(EXIT_FAILURE);
}
}
在这个例子中,我可能对 fclose
有疑问。我无法关闭 stdin
和 stdout
。我怎样才能正确和有条件地关闭 fp
?
我必须关闭 fp
吗?
fclose() returns 0 如果文件成功关闭但在您的代码中
if(!fclose(fp)) {
exit(EXIT_FAILURE);
}
如果 fclose() 成功关闭文件 main() return EXIT_FAILURE,那么你可以将其更改为
if(fclose(fp)) {
exit(EXIT_FAILURE);
}
或
if(fclose(fp)!=0){
exit(EXIT_FAILURE);
}
编辑:
The question is more: must I close fp if it is not stdin or stdout?
if( (fp!=stdin) && (fp!=stdout) )
if( fclose(fp) )
exit(EXIT_FAILURE);
或
if( (fp!=stdin&&fp!=stdout) && fclose(fp) )
exit(EXIT_FAILURE);
因为 && 是 short-circuiting operator 并且保证从左到右求值