我开始在 Visual Studio (C) 中编程,我只是尝试一一打印文件中的值。我可以在我的 Eclipse 版本中轻松地做到这一点。 (这是完全相同的代码)。我的 txt 文件位于项目文件夹中,如下所示: https://i.imgur.com/SPjZOrN.png
代码如下:
#include <stdio.h>
int main(int argc, char **argv) {
int c;
FILE *file;
const char* file_name = "ECG.txt";
file = fopen(file_name, "r");
int i = 0;
fscanf(file, "%d", &i);
while (!feof(file))
{
printf("%d ", i);
fscanf(file, "%d", &i);
}
fclose(file);
return 0;
}
当我运行这个程序时,我收到错误流!= nullptr 我该如何解决这个问题?
最佳答案
您的程序很可能尝试从可执行文件所在的目录加载文件,而不是从源文件所在的目录加载文件(如您所愿)。
将 ECG.txt
文件放置在目标目录中或使用绝对路径,例如“c:/myuser/myproject/ECG.txt”
;
始终检查fopen
的结果。如果结果为 NULL,则无法打开文件(可能是运行时错误的原因)。因此,程序的相关部分可能如下所示:
file = fopen(file_name, "r");
if (file) {
int i = 0;
while (fscanf(file, "%d", &i)==1) {
printf("%d ", i);
}
fclose(file);
} else {
printf("error opening file");
}
关于c - Stream != nullptr Visual Studio,简单地打印 txt 文件中的值 (C),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52403303/