嵌入式学习记录 2024.5.6(fprintf和fscanf练习)

5.6号部分io函数

有如下结构体

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 <stdio.h>
#include <string.h>
#include <stdlib.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 s[5] = {
        {"zhangsan", 20, 100, 90, 100, 100, 100, 100},
        {"lisi", 21, 100, 100, 100, 100, 100, 100},
        {"wang", 22, 100, 100, 100, 100, 100, 100},
        {"liliu", 23, 100, 90, 100, 100, 100, 100},
        {"zhangwu", 24, 100, 90, 100, 100, 100, 100}
    };
    FILE* fp = fopen("./zuoye.txt", "w");
    for (int i = 0; i < 5; i++) {
        fprintf(fp, "%s %d %lf %lf %lf %lf %lf %lf\n",
		 s[i].name, s[i].age, s[i].math_score, s[i].chinese_score, 
		 s[i].english_score, s[i].physics_score, s[i].chemistry_score, s[i].bio_score);
    }         
    fclose(fp);

    fp = fopen("./zuoye.txt", "r");
    struct Student s2[5];
    for (int i = 0; i < 5; i++) {
        fscanf(fp, "%s %d %lf %lf %lf %lf %lf %lf\n", 
		s2[i].name, &s2[i].age, &s2[i].math_score, &s2[i].chinese_score,
		 &s2[i].english_score, &s2[i].physics_score, &s2[i].chemistry_score, &s2[i].bio_score);
    }
    fclose(fp);

    for (int i = 0; i < 5; i++) {
        printf("%s %d %.2lf %.2lf %.2lf %.2lf %.2lf %.2lf\n", 
		s2[i].name, s2[i].age, s2[i].math_score, s2[i].chinese_score, 
		s2[i].english_score, s2[i].physics_score, s2[i].chemistry_score, s2[i].bio_score);
    }

    return 0;
}
zhangsan 20 100.00 90.00 100.00 100.00 100.00 100.00
lisi 21 100.00 100.00 100.00 100.00 100.00 100.00
wang 22 100.00 100.00 100.00 100.00 100.00 100.00
liliu 23 100.00 90.00 100.00 100.00 100.00 100.00
zhangwu 24 100.00 90.00 100.00 100.00 100.00 100.00

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值