/*** write.c ***/ #include<stdio.h> #include<string.h> struct student { char name[10]; int age; }; int main() { struct student st[10] = {0}; int i; for(i = 0; i < 10; i++) { printf("please input name:\n"); scanf("%s",st[i].name); printf("please input age:\n"); scanf("%d",&st[i].age); } FILE *p = fopen("./a.txt","w"); fwrite(st,sizeof(struct student),10,p); fclose(p); }
#include<stdio.h> #include<string.h> struct student { char name[100]; int age; }; int main() { struct student st = {0}; FILE *p = fopen("./a.txt","rb"); while(!feof(p)) { memset(&st,0,sizeof(struct student)); fread(&st,sizeof(struct student),1,p); printf("name = %s , age = %d\n",st.name,st.age); } fclose(p); return 0; }
Read data read operation results wrong.
/***
write.c
***/
#include<stdio.h>
#include<string.h>
struct student
{
char name[10];
int age;
};
int main ()
{
struct student st[10] = {0};
int i;
for(i = 0; i < 10; i++)
{
printf("please input name:\n");
scanf("%s",st[i].name);
printf("please input age:\n");
scanf("%d",&st[i].age);
}
FILE *p = fopen("./a.txt","w");
fwrite(st,sizeof(struct student),10,p);
fclose(p);
}