我正在尝试写入一个文件并向其追加数据。
这是我的代码片段。 thresh 是一个无符号的 short。
FILE *fp_th;
fp_th = fopen("threshold.txt", "a");
printf("opening file failed: %s\n", strerror(errno));
fprintf(fp_th,"%d ", thresh);
fclose(fp_th);
之前它运行良好,但我更改了一些代码,突然间它不再打印了。
我已经确认 fopen 没有打开文件流
printf(" check fp_th = %p \n", fp_th);
它打印出 check fp_th = 00000000
。
编辑:在 fopen 之后添加 printf("opening file failed: %s\n", strerror(errno));
。输出说没有错误。它在说谎吗?奇怪的..
奇怪的是,我正在编写并附加一个类似的文件,但该文件工作正常。如何解析返回 NULL 的 fopen?为什么会这样?谢谢!
最佳答案
首先
fprintf(fp_th,"%d ", thresh);
通常会缓冲输出,直到您关闭文件或内部 FILE* 缓冲区已满。您可能不会立即在文件中看到任何输出
您可以 fflush() FILE*,以便在您决定时将其写入文件。
fprintf(fp_th,"%d ", thresh);
fflush(fp_th);
其次
printf(" check fp_th = %d \n", fp_th);
这不会检查 fp_th
是否无效。它只是将 fp_th 的指针值打印为有符号整数,而 -7323824 可能与任何值一样好,这将更没有意义,如果指针的大小与一个整数。
要打印一个指针,你应该使用 %p
printf(" check fp_th = %p \n", fp_th);
如果失败,fopen 返回 NULL,您应该检查它以了解打开文件是否失败。
FILE *fp_th;
fp_th = fopen("threshold.txt", "a");
if(fp_th == NULL) {
printf("opening file failed: %s\n", strerror(errno));
return;
}
关于c - fopen 没有打开文件流...我该如何解决这个问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5021819/