我正在尝试逐行读取并将值放在稍后将使用的整数上。我使用 fgets 并且它返回 0 并且没有进入 while 循环,现在我正在使用 fscanf 它返回 -1 并且我也无法进入 while 循环。我将在这里插入代码段和我使用的文本文件。
FILE *f;
f = fopen( fileNames[i], "r");
if (f == NULL) {
printf("Failed to open a file\n");
}
int number;
printf("fscanf value %d\n", (fscanf( f, "%d", &number))); //returns -1 always
while( fscanf( f, "%d", &number) > 0){ // does NOT get into the while loop
for(int i = 0; i < intervalCount; i++){
if( // operations I use in my project ){
// operations that I will use in my project
}
}
}
fclose(f);
文本文件类似于1534
1535
1420
1400
1600
1601
2500
1536
1537
1538
请帮忙,我真的不明白是什么问题。澄清一下 - f 不是 NULL,它不会进入 if 语句。
最佳答案
如果 fopen()
则应退出该函数失败,否则在调用 fscanf()
时会出现未定义的行为带有一个空指针。
更一般地,您应该在诊断消息中输出更多信息,以帮助找出这些调用失败的原因。
在调试器中单步执行也是一种好方法。
#include <errno.h>
#include <stdio.h>
#include <string.h>
[...]
FILE *f;
f = fopen(fileNames[i], "r");
if (f == NULL) {
fprintf(stderr, "Failed to open file %s: %s\n",
fileNames[i], strerror(errno));
} else {
int number;
int res = fscanf(f, "%d", &number);
if (res != 1) {
fprintf(stderr, "reading from %s: fscanf returns %d\n",
fileNames[i], res);
} else {
while (fscanf(f, "%d", &number) == 1) {
for (int i = 0; i < intervalCount; i++) {
if (// operations I use in my project) {
// operations that I will use in my project
}
}
}
}
fclose(f);
}
关于c - fscanf 返回 -1,fgets 返回 0 但 fopen 正在工作,这是什么问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71336000/