从文本文件中读取会跳过第一行

Reading from text file skips first line

我正在使用 strtok 从如下所示的文件中读取。感谢我上一个问题的回答,段错误消失了。但是,我现在遇到了读入文件的问题,没有在第一行被读取

再一次:我有一个看起来像这样的文件 (test.txt)

5f6
2f6

还有一个看起来像这样的 c 文件:

#include <ncurses.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>

int main(int argc, char * argv[])
{
    char buf[100];
    char *ptr;
    char *ptr2;
    char *ptr3;
    char *ptr4;
    int a,b,c,d;
    FILE *file;

    initscr();
    cbreak();
    noecho();

    if (argc > 1)
     {
        file = fopen(argv[1], "r");
        if (file == NULL) //doesn't return null
            return -1;
        while (fgets(buf,100,file) != NULL)
         {
            ptr  = strtok(buf,"f");
            ptr2 = strtok(NULL," ");
            ptr3 = strtok(NULL,"f");
            ptr4 = strtok(NULL," ");
            if (ptr != NULL)
                a = atoi(ptr);
            if (ptr2 != NULL)
                b = atoi(ptr2);
            if (ptr3 != NULL)
                c = atoi(ptr3);
            if (ptr4 != NULL)
                d = atoi(ptr4);

            mvprintw(0,0,"Values are a %d b %d c %d d %d",a,b,c,d);
         }
     }
    refresh();
    getchar();
    endwin();

    return 0;
}

从文本文件中,值应该是(预期输出):a = 5, b = 6, c = 2, d = 6;

但是程序输出:a = 2, b = 6, c = 0, d = 0

我已经尝试修改文本文件的条目(更改周围的值),但这似乎没有产生任何改进。我也尝试过更改目录,用一个新文件在另一个目录中重新编写此代码(以防这是某种内存问题,但都无济于事。)任何帮助将不胜感激。

两件事:fgets 将读取行,即直到找到换行符或缓冲区已满。使用您当前的文件布局,您无法通过一个 fgets.

获得所有四个值

您实际上从文件中读取了两行,但是您覆盖了结果,因为您没有前进光标位置;你总是写在 (0, 0)。所以你只能看到最后一行的值。