思维导图:
有如下结构体
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>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <pthread.h>
#include <semaphore.h>
#include <wait.h>
#include <signal.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <sys/ipc.h>
#include <sys/sem.h>
#include <semaphore.h>
#include <sys/msg.h>
#include <sys/shm.h>
#include <sys/un.h>
#define MAX 5
typedef struct Student{char name[16];int age;double math_score;double chinese_score;double english_score;double physics_score;double chemistry_score;double dio_score;
}std,*std_p;
int main(int argc, const char *argv[])
{std_p S=(std_p)malloc(sizeof(std)*MAX);if(S==NULL){printf("fail to apply!\n");return -1;}for(int i=0;i<MAX;i++){printf("please enter name:");gets((S+i)->name);printf("please enter age:");scanf("%d",&(S+i)->age);printf("please enter math_score:");scanf("%lf",&(S+i)->math_score);printf("please enter chinese_score:");scanf("%lf",&(S+i)->chinese_score);printf("please enter english_score:");scanf("%lf",&(S+i)->english_score);printf("please enter physics_score:");scanf("%lf",&(S+i)->physics_score);printf("please enter chemistry_score:");scanf("%lf",&(S+i)->chemistry_score);printf("please enter dio_score:");scanf("%lf",&(S+i)->dio_score);getchar();putchar(10);}FILE* fp=fopen("./text","a");if(fp==NULL){perror("fppen");return 1;}for(int i=0;i<MAX;i++){fprintf(fp,"%s\n",(S+i)->name);fprintf(fp,"%d\n",(S+i)->age);fprintf(fp,"%lf\n",(S+i)->math_score);fprintf(fp,"%lf\n",(S+i)->chinese_score);fprintf(fp,"%lf\n",(S+i)->english_score);fprintf(fp,"%lf\n",(S+i)->physics_score);fprintf(fp,"%lf\n",(S+i)->chemistry_score);fprintf(fp,"%lf\n",(S+i)->dio_score);}fclose(fp);FILE* fp1=fopen("./text","a+");if(fp==NULL){perror("fopen");return 1;}for(int i=0;i<MAX;i++){fscanf(fp1,"%s\n",(S+i)->name);fscanf(fp1,"%d\n",&(S+i)->age);fscanf(fp1,"%lf\n",&(S+i)->math_score);fscanf(fp1,"%lf\n",&(S+i)->chinese_score);fscanf(fp1,"%lf\n",&(S+i)->english_score);fscanf(fp1,"%lf\n",&(S+i)->physics_score);fscanf(fp1,"%lf\n",&(S+i)->chemistry_score);fscanf(fp1,"%lf\n",&(S+i)->dio_score);}fclose(fp1);for(int i=0;i<MAX;i++){printf("name:%s\n",(S+i)->name);printf("age:%d\n",(S+i)->age);printf("math_score:%lf\n",(S+i)->math_score);printf("chinese_score:%lf\n",(S+i)->chinese_score);printf("english_score:%lf\n",(S+i)->english_score);printf("physics_score:%lf\n",(S+i)->physics_score);printf("chemistry_score:%lf\n",(S+i)->chemistry_score);printf("dio_score:%lf\n",(S+i)->dio_score);}return 0;
}
终端运行结果:
保存文件内容: