首页 > 代码库 > c 结构体读取与保存
c 结构体读取与保存
1.结构体保存到文本
1 #include <stdio.h> 2 #include <stdlib.h> 3 #include <string.h> 4 #define max 3 5 6 typedef struct student{ 7 char name[10]; //最好用数组,方便,用指针到时写入到文本不好操作 8 int age; 9 int score;10 }STU;11 int size = sizeof(STU);12 void write(STU *);13 void input(STU *); 14 void output(STU *);15 //void clean(STU *); 16 17 void main(void)18 {19 STU kang[max];20 input(kang);21 output(kang);22 write(kang); 23 clean(kang);24 }25 26 void input(STU * student)27 {28 char temp[10];29 int i=0;30 while(i<max && fgets(temp,sizeof(temp),stdin)!=NULL && temp[0]!=‘\0‘ )31 {32 //student->name = (char *) malloc(strlen(temp)+1); 33 strcpy(student->name,temp);34 puts("age ?"); 35 scanf("%d",&student->age);36 puts("score ?");37 scanf("%d",&student->score);38 39 while(getchar() != ‘\n‘)40 continue;41 42 student++;43 i++;44 if(i<max)45 puts("next name");46 }47 48 }49 50 void output(STU * student)51 {52 int i=0;53 while(i<max)54 {55 printf("%d---%s---%d---%d\n",i,student->name,student->age,student->score);56 i++;57 student++;58 }59 60 }61 62 void write(STU * student)63 {64 FILE *fp;65 int i=0;66 if( (fp=fopen("data.txt","w+b")) == NULL )67 {68 puts("open error");69 }70 71 while(i<max)72 {73 fwrite(student,size,1,fp);74 i++;student++;75 }76 77 fclose(fp);78 79 }80 81 void clean(STU * student)82 {83 int i=0;84 while(i<max)85 {86 free(student->name);87 i++;88 student++;89 }90 }
2.读取结构体
1 #include <stdio.h> 2 #include <stdlib.h> 3 #define max 3 4 5 typedef struct student{ 6 char name[10]; 7 int age; 8 int score; 9 }STU;10 int size = sizeof(STU);11 void read(STU *);12 13 void main(void)14 {15 STU kang[max];16 read(kang); 17 18 int i=0;19 while(i<max)20 {21 printf("%s---%d---%d\n",kang[i].name,kang[i].age,kang[i].score);22 i++;23 } 24 25 }26 27 28 void read(STU * student)29 {30 FILE *fp;31 int i=0;32 if( (fp=fopen("data.txt","a+b")) == NULL )33 {34 puts("open error");35 exit(1);36 }37 rewind(fp);38 while(i<max)39 { 40 fread(student,size,1,fp);41 student++;i++;42 } 43 44 fclose(fp);45 46 }
c 结构体读取与保存
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。