我不明白为什么这似乎失败了2的错误:
char debugText [256];
sprintf (debugText, "C:\\List.txt");
dfile = fopen( debugText, "w");
fprintf ( dfile, " err %d \n", errno);
Run Code Online (Sandbox Code Playgroud)
我说似乎是因为当dfile为NULL时,文件被创建并填充我的输出.
那么发生了什么 ?
所有这一切都告诉你,errno你的fopen电话号码值为2 .您不知道呼叫失败,因为您没有检查是否dfile == NULL.如果输出实际写入文件,可能是fopen调用成功,并且errno值从之前的某个调用中遗留下来,可能是您没有明确表示的.
失败的呼叫可以设置errno为某个非零值,但成功的呼叫不设置errno为0.要检查错误,您需要
errno通话前设为0;errno调用后的值- 但前提是您知道它失败(否则值errno无意义).如果defile == NULL,则fprintf调用具有未定义的行为; 它可能会失败.
另一方面,你说dfile是的NULL.你怎么知道?您的代码不会检查它.(如果fopen呼叫确实失败了,那么C:\List.txt你的程序的上一次运行可能会留下什么内容吗?)
你从这个程序得到什么输出?
#include <stdio.h>
#include <errno.h>
int main(void) {
char debugText [256];
FILE *dfile;
sprintf (debugText, "C:\\List.txt");
dfile = fopen( debugText, "w");
if (dfile == NULL) {
printf("fopen failed, errno = %d\n", errno);
}
else {
printf("fopen succeeded\n");
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
2 ENOENT No such file or directory. A component of a specified pathname
did not exist, or the pathname was an empty string.
Run Code Online (Sandbox Code Playgroud)
这是错误代码的列表:
http://www.thegeekstuff.com/2010/10/linux-error-codes/
但是您应该检查是否首先fopen()返回,NULL因为该值errno可能是其他值遗留下来的。
没有库函数设置errno为零。
您应该只errno在函数报告错误后进行检查。
例如,您的代码应该是:
if ((dfile = fopen(debugText, "w")) == 0)
...then fopen() failed and errno is relevant...
Run Code Online (Sandbox Code Playgroud)
如果函数没有报告失败,则输入的值errno可以是任何值。例如,在 Solaris 上,您经常会在操作成功后以errnoset toENOTTY结束,因为stdout没有连接到终端。这并不意味着实际上出了什么问题;它只是意味着测试标准输出是否是终端失败(因为它不是终端)。