c - fscanf 返回 -1,fgets 返回 0 但 fopen 正在工作,这是什么问题?

标签 c linux ubuntu scanf

我正在尝试逐行读取并将值放在稍后将使用的整数上。我使用 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/

相关文章:

php - 为什么crontab不能按时执行

linux - 在 linux 上,如何将文本环绕命令的输出并将其保存到文件中?

c - avcodec_get_name 在 Ubuntu libavcodec 中不可用,我应该使用什么?

scanf() 能否将非零输入变为零

c - 为什么我的输出数字不返回输入的输入?

c - 结构中的变量收到未声明的错误(在此函数中首次使用)

php - 从php脚本在linux中调用hello_word

c - 为什么套接字读取的数据多于实际发送的数据?

java - 没有 USB 设备识别 libusbJava/ubuntu 13.04

c - 结构内部具有未初始化大小的数组