用二进制的方式写读文件
fwrite函数写文件
#include<stdio.h>
#include<cstring>
typedef struct student{
char name[50];
int age;
}stu;
int main(){
stu s[3] = {
{"小王",18},
{"小李",20},
{"小明",25}
};
FILE *fp;
//打开文件
fp = fopen("D:/test2.txt","w");
if(fp==NULL){
perror("fopen");
return -1;
}
//用二进制方式写文件
int i;
int result = fwrite(s,sizeof(stu),3,fp);//意义:把3个大小为sizeof(stu)字节的结构体s存入到fp所指向的文件中
printf("%d\n",result);
//关闭文件
fclose(fp);
fp=NULL;
return 0;
}
fread函数读文件
#include<stdio.h>
#include<cstring>
typedef struct student{
char name[50];
int age;
}stu;
int main(){
FILE *fp;
stu s[10];
//打开文件
fp = fopen("D:/test2.txt","r");
if(fp==NULL){
perror("fopen");
return -1;
}
//用二进制方式读文件
int i;
int result = fread(s,sizeof(stu),3,fp);//意义:从fp所指的文件中读取3个大小为sizeof(stu)字节的数据,存入s中
printf("%d\n",result);
for(i=0;i<3;i++){
printf("name=%s,age=%d\n",s[i].name,s[i].age);
}
//关闭文件
fclose(fp);
fp=NULL;
return 0;
}