5.6课程作业

有如下结构体

struct  student

{

        char name[16];

        int age;

        double math_score;

        double chinese_score;

        double english_score;

        double physics_score;

        double chemistry_score;

        double bio_score;

};

 申请该结构体数组,容量为5,初始化5个学生的信息

使用fprintf将数组中的5个学生信息,保存到文件中去

下一次程序运行的时候,使用fscanf,将文件中的5个学生信息,写入(加载)到数组中去,并直接输出学生信息

#include <sys/un.h>
struct student
{
    char name[16];
    int age;//年龄
    double math_score;//数学
    double chinese_score;//语文
    double english_score;//英语
    double physics_score;//物理
    double chemistry_score;//化学
    double bio_score;//生物
};

int main(int argc, const char *argv[])
{
    //定义一个结构体数组
    struct student students[5] = {{"Alice",18,90.5,85.0,92.0,88.0,90.0,86.5},
        {"Bob",19,88.0,92.5,85.0,80.0,85.0,89.0},
        {"Lucy",18,97.0,88.0,76.5,66.0,78.0,67.0},                                             
        {"Eve",19,77.8,89.7,99.0,48.9,87.6,67.8},
        {"Gray",18,98.7,66.7,78.9,88.9,78.6,64.9}};
    //将数组中的学生信息保存到文件
    FILE *file = fopen("students.dat","w");
    if(file == NULL)
    {
        perror("打开文件失败\n");
        return 1;
    }
    for(int i=0;i<5;i++)
    {
        fwrite(&students[i],sizeof(struct student),1,file);
    }
    fclose(file);

    //假设这是下一次程序运行
    //从文件中加载学生信息到数组
    struct student loaded_students[5];
    file = fopen("students.dat","r");
    if(file == NULL)
    {
        perror("打开文件失败\n");
        return 1;
    }
    for(int i=0;i<5;++i)
    {
        fread(&loaded_students[i],sizeof(struct student),1,file);
    }
    fclose(file);
    //直接输出学生信心
    for(int i=0;i<5;++i)
    {
        printf("Name:%s,Age:%d\n",loaded_students[i].name,loaded_students[i].age);
        printf("Math:%.lf,Chinese:%.lf,English:%.lf\n",loaded_students[i].math_score,
                loaded_students[i].chinese_score,loaded_students[i].english_score);
        printf("Physics:%.lf,Chemistry:%.lf,Biology:%.lf\n",loaded_students[i].physics_score,
                loaded_students[i].chemistry_score,loaded_students[i].bio_score);
    }
    return 0;
}

运行结果

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Yoyozi_wu

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值