我不明白为什么这看起来失败了,错误号为2:
char debugText [256];
sprintf (debugText, "C:\\List.txt");
dfile = fopen( debugText, "w");
fprintf ( dfile, " err %d \n", errno);
我之所以说似乎是因为,当dfile为NULL时,文件会被创建并被我的输出填充。
那么到底是怎么回事呢?
发布于 2013-04-02 06:38:35
所有这些都告诉您,在fopen
调用之后,errno
的值是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;
}
发布于 2013-04-02 06:34:14
2 ENOENT No such file or directory. A component of a specified pathname
did not exist, or the pathname was an empty string.
以下是错误代码列表:
http://www.thegeekstuff.com/2010/10/linux-error-codes/
但是您应该先检查fopen()
是否返回了NULL
,因为errno
中的这个值可能是从其他地方遗留下来的。
发布于 2013-04-02 06:51:08
任何库函数都不会将errno
设置为零。
您应该仅在函数报告错误后才检查errno
。
例如,你的代码应该是:
if ((dfile = fopen(debugText, "w")) == 0)
...then fopen() failed and errno is relevant...
如果函数不报告故障,则errno
中的值可以是任何值。例如,在Solaris上,在成功操作之后,您通常会将errno
设置为ENOTTY
,因为stdout
没有连接到终端。这并不意味着实际上出了什么问题;它只是意味着测试标准输出是否为终端失败(因为它不是终端)。
https://stackoverflow.com/questions/15753090
复制相似问题