C fopen 写入失败,errno 为 2

标签 c fopen errno

我不明白为什么这似乎失败了,errno 为 2:

char debugText [256];
sprintf (debugText, "C:\\List.txt");
dfile = fopen( debugText, "w");
fprintf ( dfile, "  err %d \n", errno);

我说似乎是因为当 dfile 为 NULL 时,文件被创建并充满了我的输出。

这是怎么回事?

最佳答案

所有这一切告诉您的是 errno 在您调用 fopen 之后的值为 2。你不知道调用失败,因为你没有检查是否 dfile == NULL。如果输出实际上写入了文件,则可能是 fopen 调用成功并且 errno 值是之前某个调用遗留下来的,很可能是您没有明确进行的调用。

失败的调用可以将 errno 设置为某个非零值,但成功的调用不要errno 设置为 0。检查错误,你需要

  • 调用前设置errno为0;
  • 发起调用并检查它返回的值,看它是成功还是失败;和
  • 在调用后检查 errno 的值——但只有你知道它失败了(否则 errno 的值是没有意义的) .

如果 defile == NULL,则 fprintf 调用具有未定义的行为;它可能会失败。

另一方面,您说 dfileNULL。你怎么知道?您的代码不检查它。 (如果 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;
}

关于C fopen 写入失败,errno 为 2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15753090/

相关文章:

C - 访问矩阵中的特定行或列

c - 绑定(bind)错误 (99) : Cannot assign requested address

c - 用C中的矩阵绘制实心圆

c - C语言中如何截断文件?

c - 在C中发送图像文件

C - 无法从 Xcode 创建新的 .txt 文件

python - 创建一堆表时出现神秘的 "errno 150"Mysql.connector python

c++ - stdio 总是设置 errno 吗?

c - 在 C 中读入结构数组时只打印 txt 文件的最后一行

php - session 数据的 file_get_contents(或 curl 或 fopen)问题