下面的示例,存储数据块到E盘下file2.txt,让后读取出来显示在屏幕上:#include<stdio.h>
//定义结构体并初始化
struct person
{
char name[20];
char Phone[15];
char age[5];
}Myperson[3]=
{
{"小明","13611112222","21"},
{"小华","13511112222","23"},
{"小强","13811112222","30"}
};
int main(){
struct person P[3]; //创建P数组用来接受读出的数据
FILE * filepoint;
filepoint=fopen("E://file2.txt","w"); //写入方式
if(filepoint==NULL)
{
printf("\n Open file failed !");
return 1;
}
//写入文件
fwrite(Myperson,sizeof(struct person),3,filepoint);
fclose(filepoint);
//读取文件
filepoint=fopen("E://file2.txt","r"); //读取方式
if(filepoint==NULL)
{
printf("\n Open file failed !");
return 1;
}
fread(P,sizeof(struct person),3,filepoint);
printf("\n%s %s %s",&P[0].name,&P[0].Phone,&P[0].age);
printf("\n%s %s %s",&P[1].name,&P[1].Phone,&P[1].age);
printf("\n%s %s %s\n",&P[2].name,&P[2].Phone,&P[2].age);
fclose(filepoint);
return 0;
}
|