如何从C中的.txt文件读取数据?

时间:2019-05-08 18:57:26

标签: c file structure

我想在我创建的程序中读取保存在txt文件中的信息。但是当我想通过阅读来仅进行第一行学生信息阅读的过程时,例如,班级10的人在程序中编写相同的学生信息10次。我正在for循环中进行读取操作。

struct student{

char Name[30];
char Surname[30];
int StudentNumber;
int MathematicScore;
int EnglishScore;
int HistoryScore;
int BiologyScore;
int LiteratureScore;
int PhysicsScore;
int classNum;
int total;
float average;

};

/ *打印过程* /

FILE *fout;
fout = fopen("Mathematic 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.MathematicScore);

    x.total = x.total + x.MathematicScore;

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

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

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

fclose(fout);



/* Reading process */



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


    fscanf(fin, "Class Number : %d\n\n%s %s %d %d\n",&x.classNum, &x.Name, &x.Surname, &x.StudentNumber, &x.MathematicScore, &x.average);
    fclose(fin);            


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

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

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

    }

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

1 个答案:

答案 0 :(得分:0)

以下是我初看时遇到的问题:

  1. 在读取过程中,您只能调用fscanf()一次。如果您想读取多个学生的数据,就像您在编写过程中正在做的那样,则需要为每个学生调用一次以从文件中读取该学生的行。

  2. 在您的阅读/打印过程中,您正在x.classNum次打印相同的数据。