文件与结构体
#include<stdio.h>#include<stdlib.h>
#define N 5
struct students{
char name[10];
int age;
double tizhong;
}student[N];
void save()
{
FILE*fp;
if((fp=fopen("xxg.txt","wb"))==NULL)
{printf("文件打开失败\n");exit(0);}
for(int i=0;i<N;i++)
if(fwrite(&student[i],sizeof(struct students),1,fp)!=1)
printf("文件写入失败!\n");
fclose(fp);
}
void out()
{
FILE*fp;
if((fp=fopen("xxg.txt","rb"))==NULL)
{printf("文件打开失败\n");exit(0);}
for(int i=0;i<N;i++)
{fseek(fp,i*sizeof(struct students),0);//随机读取数据,在fseek中,起始点为0.
fread(&student[i],sizeof(struct students),1,fp);
printf("%-10s%-4d%4.2f\n",student[i].name,student[i].age,student[i].tizhong);
}
fclose(fp);
}
int main()
{
printf("请输入学生信息!\n");
for(int i=0;i<N;i++)
scanf("%s%d%lf",student[i].name,&student[i].age,&student[i].tizhong);
save();
printf("输出文件信息\n");
out();
return 0;
}