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

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

//写入磁盘函数
void save ()
{
    int i;
    FILE *fp;
    if ((fp=fopen("student_list.txt","wd"))==NULL)
    {
        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次)
        {
            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);
    }
}

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

    return 0;
}
JSRUN前端笔记, 是针对前端工程师开放的一个笔记分享平台,是前端工程师记录重点、分享经验的一个笔记本。JSRUN前端采用的 MarkDown 语法 (极客专用语法), 这里属于IT工程师。