我不理解为什么这似乎失败了,而且 errno 是 2:
char debugText [256];
sprintf (debugText, "C:\\List.txt");
dfile = fopen( debugText, "w");
fprintf ( dfile, " err %d \n", errno);
我之所以说“似乎”是因为当dfile为空时,文件会被创建并填充我的输出内容。
那么到底发生了什么?
fopen
调用后,errno
的值为2。你不知道调用是否失败,因为你没有检查dfile == NULL
。如果输出实际上是写入文件的,那么fopen
调用成功了,errno
的值可能来自以前的某个调用,很可能是你没有明确进行的调用。fopen
调用完全有可能将errno
设置为非零值。errno
设置为一些非零值,但成功的调用不会将errno
设置为0。要检查错误,您需要:
errno
设置为0;errno
的值——但仅当您知道它失败时(否则errno
的值毫无意义)。dfile == 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;
}
defile == NULL
,如果是,则不要尝试写入文件。为了验证 fopen()
失败的原因,请按照我建议的使用 errno
。假设你在 Windows 系统上,打开 "C:\\List.txt"
以进行输出不应该出现 errno==2
的错误,这意味着“没有这样的文件或目录”。(你确实在使用 Windows 吗?而不是在 Cygwin 下?) - Keith Thompson2 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
中的值可能是从其他地方遗留下来的。
没有任何库函数会将errno
设置为零。
只有在函数报告错误后才应该检查errno
。
例如,您的代码应该是:
if ((dfile = fopen(debugText, "w")) == 0)
...then fopen() failed and errno is relevant...
如果函数没有报告错误,那么errno
中的值可能是任意的。例如,在Solaris上,您经常在成功操作后将errno
设置为ENOTTY
,因为stdout
未连接到终端。这并不意味着实际上发生了任何错误;它只是意味着是否标准输出是终端的测试失败了(因为它不是终端)。
dfile == NULL
;实际上,由于接下来的 fprintf()
使用了它,所以 dfile
为空的可能性很小(如果它为空,你可能会在 fprintf()
中崩溃)。你需要修改代码以显式测试 dfile
,然后我才愿意相信你的断言 dfile
为空(并将错误报告到除 dfile
之外的通道)。 - Jonathan Leffler只需编写文件名: 像下面的示例一样,对我来说效果很好: 它将创建文件并在其中写入用户输入的数字。
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#include<string.h>
#include<errno.h>
void main() {
int num;
FILE *fptr;
clrscr();
fptr = fopen("num.txt","w");
if(fptr == NULL)
{
fprintf(stderr,"open error for %s,errno = %d: %s\n",fptr, errno, strerror(errno));
printf("Error!");
exit(1);
}
printf("Enter num: ");
scanf("%d",&num);
fprintf(fptr,"%d",num);
fclose(fptr);
getch();
}
errno == 2
的错误;结果发现,如果文件不符合8.3规则,fopen
会返回NULL
并将errno
设置为ENOENT
。
需要指出的是,我在嵌入式系统中遇到了这种情况,在Windows上不应该出现这个问题。
dfile
是什么类型?NULL
的测试在哪里? - David Schwartzstrerror()
函数,它会返回一个解释errno
的字符串。 - Zaffy