编辑代码

#include <stdio.h>
#include <stdlib.h>
#define SIZE 2  //宏变量
//向一个磁盘文件中存入10个学生的信息(学号,姓名,成绩,)),最后读取磁盘文件验证

//定义一个结构体存存放学生的信息
struct student 
{
    int num;
    char name[10];
    float score;
}   stu1[SIZE], stu2[SIZE], information_i;

//写入磁盘函数
void save ()
{
    int i;
    FILE *fp;
    if ((fp=fopen("student_list.txt","wd"))==NULL)  //以二进制的形式,存到student_list.txt文件中(没有就新建)
    {
        printf("Cannot open tha file! \n");
        exit(0);
    }
    
    for (i=0;i<SIZE;i++)
    {
        if(fwrite(&stu1[i],sizeof(struct student),1,fp) != 1)  //stu1[i]位置对应的学生信息(结构体)存放到fp指向的文件中(存1次)/返回值为count(1)
        {
            printf("frile write error!");
        }
        fclose(fp);
    }
}

//读入内存函数(即读出磁盘打印在显示器中)
void check()
{
    int i;
    FILE *fp;
    if ((fp=fopen("student_list.txt","rd"))==NULL)
    {
        printf("Cannot open tha file! \n");
        exit(0);
    }

    for(i=0;i<SIZE;i++)
    {
        fread(&stu2[i],sizeof(struct student),1,fp);  //从fp指向的文件读入一组数据保存到stu2中
        printf("%d   %s   %4.2f\n", stu1[i].num, stu1[i].name, stu1[i].score);
    }
    fclose(fp);
}

void check_i()
{
    
    int i = 1;  //定位到第i个学生(从0开始)
    FILE *fp;
    if (!(fp=fopen("student_list.txt","r")))
    {
        printf("Cannot open tha file! \n");
        exit(0);
    }
    
    rewind(fp);     //使文件指针指向开头
    fseek(fp, i*sizeof(struct student), 0);     //从开头到移动到对应i的位置
    fread(&information_i, sizeof(struct student), 1, fp);
    printf("%d   %s   %4.2f\n", information_i.num, information_i.name, information_i.score);
    
    fclose(fp);
}

//输入学生信息
int main () {
    int i;
    printf("Please enter student information(school_number、name、score):\n");
    for (i=0;i<SIZE;i++)
    {
        scanf("%d %s %f",&stu1[i].num,stu1[i].name,&stu1[i].score);
    }
    save();
    printf("The file for student_list.txt:\n");
    check();
    printf("The information of second student:\n");
    check_i();

    return 0;
}