C程序读取文件末尾

C program reads the end of file

请查看本文末尾的编辑 我有一个 test.dat 有 2 行。 第一行是一个浮点数(5.0) 第二行是两个整数,中间用“*”隔开,比如4*3 浮点数显示正确(输出:5.0000)但第二行未显示。我的老师告诉我,我在 while 循环后犯了一个错误。 Fscanf 读取文件的结尾,而不是 beginning.That 为什么我得到随机数作为输出,例如“65746* -8634364” 我不知道,如何解决 it.Your 帮助会很好。这是我的 C 代码:

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

int main()
{
    float z1;
    int z2,z3;
    char line[255];

    FILE *file;
    file = fopen("test.dat", "r");
    if (file==NULL)
    {
        printf("Error\n");
        return 1;
    }

    fscanf(file, "%f", &z1);
    printf("%f\n", z1);

    while (fscanf(file, "%s", line)  == 1)
    {
        fscanf(file, "%d*%d", &z2, &z3);
        printf("%d * %d\n", z2,z3);
    }
    fclose(file);
    return 0;
}

编辑:按照第一个答案的说明操作后,我收到了新警告 警告代码:In function ‘main’: main.c:21:2: warning: format ‘%s’ expects argument of type ‘char *’, but argument 3 has type ‘char (*)[255]’ [-Wformat=] while (fscanf(file, "%s", &line) ==1) ^

编辑 2:警告消失了,多亏了第一个答案!!还是有问题:第二行的内容是 "4*3" ,我的输出是 "0*0" 为什么?

while (fscanf(file, "%s", &line) != EOF)
                       ^ wrong argument is passed to %s

您将字符串读入 line ,但 line 被声明为 char 变量 -

char line;                 // will invoke UB if no space is left for '[=11=]'

因此,您需要将 line 声明为 char 数组。像这样的东西 -

char line[255];            //make sure to leave a space for null character

注意-可能不要用EOF测试fscanf,写你的循环条件如下-

while (fscanf(file, "%s", line)==1)     //will return 1 only if it is successful
            /*           ^ note- don't pass here &line, just pass line  */

你用fscanf填充了一个char变量。您应该使用 char*,因为您在格式字符串中使用了 %s。