65,176
社区成员




//看这个吧,完整的,先是写入到student.dat,再从student.dat读出!
#include <stdio.h>
#define SIZE 4
struct student_type
{
char name[10];
int num;
int age;
}stud[SIZE];
void save()
{
FILE* fp;
int i;
if ((fp=fopen("student.dat","wb"))==NULL)
{
printf("can not open ifle\n");
return;
}
for (i=0;i<SIZE;i++)
{
if (fwrite(&stud[i],sizeof(struct student_type),1,fp)!=1)
{
printf("file write error\n");
}
}
fclose(fp);
}
void load()
{
FILE* fp;
int i;
if ((fp=fopen("student.dat","rb"))==NULL)
{
printf("can not open ifle\n");
return;
}
for (i=0;i<SIZE;i++)
{
fread(&stud[i],sizeof(struct student_type),1,fp);
printf("%-10s %4d %4d\n",stud[i].name,stud[i].num,stud[i].age);
}
fclose(fp);
}
void main()
{
int i;
for (i=0;i<SIZE;i++)
{
scanf("%s%d%d",stud[i].name,&stud[i].num,&stud[i].age);
}
save();
load();
}
//Result under VC6:
li 9 9
zhang 3 4
wang 3 4
liu 4 4
li 9 9
zhang 3 4
wang 3 4
liu 4 4
Press any key to continue
//这么写
#include <stdio.h>
#define SIZE 4
struct student_type
{
char name[10];
int num;
int age;
}stud[SIZE];
void save()
{
FILE* fp;
int i;
if ((fp=fopen("student.dat","wb"))==NULL)
{
printf("can not open ifle\n");
return;
}
for (i=0;i<SIZE;i++)
{
if (fwrite(&stud[i],sizeof(struct student_type),1,fp)!=1)
{
printf("file write error\n");
}
}
fclose(fp);
}
void main()
{
int i;
for (i=0;i<SIZE;i++)
{
scanf("%s%d%d",stud[i].name,&stud[i].num,&stud[i].age);
}
save();
}