从文件中读写结构体信息 例子:利用结构体数组将两个学生的信息写入一个文件中,再读取这两个学生的信息显示到屏幕上 #include <stdio.h> #include <string.h>
struct student{ char name[21]; int age; };
int main() { struct student stu[3]={{"Star",18},{"Mike",19},{"Simmon",17}};
FILE *fp=fopen("struct.data","wb+"); if(fp!=NULL){ for (int i=0; i<3; i++) { fwrite(&stu, sizeof(struct student), 1, fp); } printf("写入成功!\n"); } rewind(fp);
struct student stu2[3]; if (fp!=NULL) { for (int i=0; i<3; i++) { fread(&stu2, sizeof(struct student), 1, fp); } } for (int i=0; i<3; i++) { printf("%s %d\n",stu2.name,stu2.age); } fclose(fp);
return 0; }
|