有如下结构体
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 <unistd.h>
#include <stdlib.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>
typedef 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;
}Stu;
int main(int argc, const char *argv[])
{
Stu stu[5]=
{
{"mike",19,99,88,77,66,55,44},
{"jack",20,11,22,33,44,55,66},
{"rose",21,55,66,77,88,99,88},
{"lucy",20,66,88,66,55,11,99},
{"pony",18,99,66,88,77,55,66}
};
FILE *fp = fopen("./stu.txt","w");
if(fp==NULL)
{
perror("fopen");
return 1;
}
for(int i=0;i<5;i++)
{
fprintf(fp,"Student : %d\n",i+1);
fprintf(fp,"Student name : %s\n",stu[i].name);
fprintf(fp,"Student age : %d\n",stu[i].age);
fprintf(fp,"math_score : %lf\n",stu[i].math_score);
fprintf(fp,"chinese_score : %lf\n",stu[i].chinese_score);
fprintf(fp,"english_score : %lf\n",stu[i].english_score);
fprintf(fp,"physics_score : %lf\n",stu[i].physics_score);
fprintf(fp,"chemistry_score : %lf\n",stu[i].chemistry_score);
fprintf(fp,"bio_score : %lf\n",stu[i].bio_score);
}
fclose(fp);
fp = fopen("./stu.txt","r");
if(fp==NULL)
{
perror("fopen");
return 1;
}
char str[99999] = " ";
int i=0;
int retval;
while(retval!=EOF)
retval = fscanf(fp,"%c",str+(i++));
fclose(fp);
puts(str);
return 0;
}