I have a home assignment which says that I have to store information about a mansion in a binary file. On the first line of that file I have to keep information about how many floors there are in the building and how many apartments there are on a floor (size of two-dimensional array). And on the next lines I have to keep info about the apartments - a unique number for each apartment, number of rooms in that apartment, number of people living there, family name, date when the family moved in that apartment, monthly rent.
So, the question is: how should I store that information and how should I read it? If I use fread(buf, size, number_of_elements, FIlE *), how would I know the number of the elements? For example, how do I read a family name when I don't know it's lenght?
Thanks in advance!
PS. Thank you, claptrap! I tried to write the data first into the binary file but I got some error :(
#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);
}
}