如何从文件读取数据?我无法解决

时间:2019-05-08 15:29:41

标签: c file structure

我将学生信息记录到txt文件中,但是当我想从文件中读取数据时 只需阅读第一行中的信息即可。我也计算学生的平均数,但是当ı想阅读平均数时,它不起作用。

    FILE *fout;
fout = fopen("English Class.txt","w"); 

printf("Please enter student number of class : ");
scanf("%d", &x.classNum);

fprintf(fout, "Class Number : %d\n",x.classNum);

for(i=0; i<x.classNum; i++){

    printf("Please Enter %d.Student Name : ",i+1);
    scanf("%s",&x.Name);

    printf("Please Enter %d.Student Surname : ",i+1);
    scanf("%s",&x.Surname);

    printf("Please Enter %d.Student Number : ",i+1);
    scanf("%d",&x.StudentNumber);

    printf("Please Enter %d.Student Score : ",i+1);
    scanf("%d",&x.EnglishScore);

    x.total = x.total + x.EnglishScore;

    fprintf(fout, "\nStudent Name : %s %s Student Number : %d Student Score : %d\n", x.Name, x.Surname, x.StudentNumber, x.EnglishScore);
 }

x.average = x.total / x.classNum;

fprintf(fout, "\n\nClass Average is : %f", x.average);

fclose(fout);   

我从顶级代码获取学生记录

        FILE *fin;
    fin = fopen("English Class.txt","r");


    fscanf(fin, "Class Number : %d\nStudent Name : %s %s Student Number : %d Student Score : %d\n\nClass Average is : %f",&x.classNum, &x.Name, &x.Surname, &x.StudentNumber, &x.EnglishScore, &x.average);
    fclose(fin);            


    printf("Class Number : %d\n", x.classNum);

    for(i=0; i<x.classNum; i++){

    fscanf(fin, "\nStudent Name : %s %s Student Number : %d Student Score : %d\n\nClass Average is : %f", &x.Name, &x.Surname, &x.StudentNumber, &x.EnglishScore);
    fclose(fin);    

    printf("\nStudent Name : %s %s Student Number : %d Student Score : %d\n", x.Name, x.Surname, x.StudentNumber, x.EnglishScore);  

    }

    printf("\n\nClass Average is : %f", x.average);

1 个答案:

答案 0 :(得分:3)

截至目前,您每次阅读后都将立即关闭file

    fscanf(fin, "Class Number : %d\nStudent Name : %s %s Student Number : %d Student Score : %d\n\nClass Average is : %f",&x.classNum, &x.Name, &x.Surname, &x.StudentNumber, &x.EnglishScore, &x.average);

   fclose(fin)

然后,您尝试使用相同的FILE指针进行读取,从而导致未定义的行为。


仅在完成处理后关闭文件。