一、结构体的写入和读取
//写入结构体
FILE *fp = fopen("/Users/ios/Desktop/1.data", "w");
if (fp) {
// int num = 20;
// fwrite(&num, sizeof(num), 1, fp);//写入int
Person p = {"苍空",16}; //int num = 20;
fwrite(&p, sizeof(p), 1, fp);
printf("写完了
");
fclose(fp);
}
//读取结构体
FILE *fp = fopen("/Users/ios/Desktop/1.data", "r");
if(fp){
Person p;
fread(&p, sizeof(p), 1, fp);
printf("姓名:%s 年龄:%d
",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), 5, fp);//第二个参数:每个元素的大小,第三个:一共多少块,多少块以数组长度为结果
printf("haha
");
fclose(fp);
}
//读取数组
FILE *fp = fopen("/Users/ios/Desktop/1.xxxx", "r");
if(fp){
float fs[5];
fread(&fs, sizeof(float), 5, fp);
for (int i =0; i<5; i++) {
printf("%.1f
",fs[i]);
}
fclose(fp);
}
三、结构体数组的写入和读取
//结构体数组的写入
FILE *fp = fopen("/Users/ios/Desktop/xxx.1", "w");
if (fp) {
Person ps[4] = { {"刘",16},{"张",17},{"郭",18},{"花",14} };
fwrite(ps, sizeof(Person), 4, fp);
printf("第1个天王最帅
");
fclose(fp);
}
//结构体数组的读取
FILE *fp = fopen("/Users/ios/Desktop/xxx.1", "r");
if (fp) {
//读取
Person ps[4];
fread(ps, sizeof(Person), 4, fp);
for (int i = 0; i<4; i++) {
printf("姓名:%s 年龄:%d
",ps[i].name,ps[i].age);
}
fclose(fp);
}