我有以下代码打开了一个输入和输出文件:奇怪ç行为具有的fopen和测试NULL
if ((source_file_ptr = fopen(source_filename, "rb")) == NULL) {
error("unable to open input file");
}
if ((output_file_ptr = fopen(output_filename, "wb")) == NULL) {
error("unable to open output file");
}
这是goood简单的办法赶上在打开的文件中的错误。
但是,在对我的程序进行一些编辑后,程序现在崩溃而不是捕获无效的输出文件。
我试了几件事情没有成功,但有趣的是,当我试试这个:
if ((output_file_ptr = fopen(output_filename, "wb")) == NULL) printf("fail");
exit(0);
if ((source_file_ptr = fopen(source_filename, "rb")) == NULL) {
error("unable to open input file");
}
if ((output_file_ptr = fopen(output_filename, "wb")) == NULL) {
error("unable to open output file");
}
这将打印“失败”(显然退出而不更加深入了解)。
但是,如果我将exit(0)行注释掉,它将再次显示相同的崩溃行为,而不打印“失败”,也不会捕获错误。
我无法解释为什么这是...我怀疑是一个悬挂指针,但函数内的唯一前面的代码行已经包含在if-else if-else all with括号中。上面只有其他几个函数,但我已经检查并确保它们都被括在括号内。
我还在学习C,关于这里发生了什么的任何想法?
非常感谢!
注意:用括号括住printf(“fail”)不会改变我观察到的行为。
编辑:额外的代码如下上面:
if (fread(&file_struct, sizeof(file_struct), 1, source_file_ptr) < 1) {
error("unable to read %s", source_filename);
}
else {
error_check(file_struct);
if (fwrite(&file_struct, sizeof(file_struct), 1, output_file_ptr) < 1) {
error("unable to write file header");
}
}
你可以在这些if后面发布后续代码吗?如果遇到故障,这些'if's将打印消息,但文件指针仍可能被使用。 – hmjd 2012-03-29 11:11:49
使用'perror()'来描述错误。 – pmg 2012-03-29 11:14:48
您可能需要在printf()和exit()周围使用一些{}。 – wildplasser 2012-03-29 11:15:11