用自定义函数打开文件

img

fopen打开文件,fscanf读取数据就可以了,参考如下:

#include <stdio.h>
struct student
{
    int id;
    int score[3];
};

void ReadFile(struct student stu[],int *n)
{
    int cnt = 0;
    FILE* fp;
    if((fp=fopen("score.txt","r")) == 0)
    {
        printf("文件打开失败\n");
        return 0;
    }
    while(!feof(fp))
    {
        fscanf(fp,"%d %d %d %d\n",&stu[cnt].id,&stu[cnt].score[0],&stu[cnt].score[1],&stu[cnt].score[2]);
        if(stu[cnt].id > 0) //避免读到空行
            cnt++;
    }
    fclose(fp);
    *n = cnt; //读取的学生信息条数
}