一、结构体的写入和读取
//写入结构体
FILE *fp = fopen("/Users/ios/Desktop/1.data", "w");
if (fp) {
// int num = 20;
// fwrite(&num, sizeof(num), 1, fp);//写入int
Person p = {"苍空",}; //int num = 20;
fwrite(&p, sizeof(p), , fp);
printf("写完了\n");
fclose(fp);
}
//读取结构体
FILE *fp = fopen("/Users/ios/Desktop/1.data", "r");
if(fp){
Person p;
fread(&p, sizeof(p), , fp);
printf("姓名:%s 年龄:%d\n",p.name,p.age);
fclose(fp);
}
二、数组的写入和读取
//写入数组
FILE *fp = fopen("/Users/ios/Desktop/1.xxxx", "w");
if(fp){
float fs[] = {10.1f,10.2f,10.3f,10.4f,10.5f};//数组名本身就是地址
fwrite(&fs, sizeof(float), , fp);//第二个参数:每个元素的大小,第三个:一共多少块,多少块以数组长度为结果
printf("haha\n");
fclose(fp);
}
//读取数组
FILE *fp = fopen("/Users/ios/Desktop/1.xxxx", "r");
if(fp){
float fs[];
fread(&fs, sizeof(float), , fp);
for (int i =; i<; i++) {
printf("%.1f\n",fs[i]);
}
fclose(fp);
}
三、结构体数组的写入和读取
//结构体数组的写入
FILE *fp = fopen("/Users/ios/Desktop/xxx.1", "w");
if (fp) {
Person ps[] = { {"刘",},{"张",},{"郭",},{"花",} };
fwrite(ps, sizeof(Person), , fp);
printf("第1个天王最帅\n");
fclose(fp);
}
//结构体数组的读取
FILE *fp = fopen("/Users/ios/Desktop/xxx.1", "r");
if (fp) {
//读取
Person ps[];
fread(ps, sizeof(Person), , fp);
for (int i = ; i<; i++) {
printf("姓名:%s 年龄:%d\n",ps[i].name,ps[i].age);
}
fclose(fp);
}