我有一个家庭作业,说我必须将有关豪宅的信息存储在二进制文件中。在该文件的第一行,我必须保留有关建筑物中有多少层以及一层有多少公寓的信息(二维数组的大小)。在接下来的几行中,我必须保留有关公寓的信息——每间公寓的唯一编号、该公寓的房间数量、住在那里的人数、姓氏、家庭搬入该公寓的日期、月租金。
所以,问题是:我应该如何存储这些信息以及我应该如何阅读它?如果我使用 fread(buf, size, number_of_elements, FIlE *),我怎么知道元素的数量?例如,当我不知道姓氏的长度时,如何阅读它?
提前致谢!
PS。谢谢你,拍手!我试图先将数据写入二进制文件,但出现了一些错误:(
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#define NAPARTMENTS 21
#define TAX_ADULT 3
#define TAX_KID 1
#define TAX_ELEVATOR 2
#define NFLOORS 7
#define NROOMS 3
void main()
{
FILE *fp;
int i, j;
struct info_apartments
{
unsigned numApartment, numRooms, numAdults, numKids, rent;
char family[30], date[10];
};
typedef struct info_apartments data;
data apartments[7][3];
for(i=0; i<NFLOORS; i++)
for(j=0; j<NROOMS; j++)
{
apartments[i][j].numApartment=i*10+j+1;
printf("\nEnter the number of the rooms: ");
scanf("%d", apartments[i][j].numRooms);
printf("\nEnter number of adults: ");
scanf("%d", apartments[i][j].numAdults);
printf("\nEnter number of kids: ");
scanf("%d", apartments[i][j].numKids);
printf("\nEnter family name: ");
scanf("%s", apartments[i][j].family);
printf("\nEnter date: ");
scanf("%s", apartments[i][j].date);
//first two floors don't pay for elevator
if(i+1<3)
apartments[i][j].rent=(TAX_ADULT*apartments[i][j].numAdults)+(TAX_KID*apartments[i][j].numKids);
else
apartments[i][j].rent=((TAX_ADULT+TAX_ELEVATOR)*apartments[i][j].numAdults)+((TAX_KID+TAX_ELEVATOR)*apartments[i][j].rent);
}
if((fp=fopen("myfile", "ab"))==NULL)
{
printf("Error");
exit(1);
}
if((fwrite(apartments, sizeof(apartments), 1, fp))!=1)
{
printf("Error!\n");
exit(1);
}
}