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