-
fread/fwrite problems
Greetings master coders.
Earlier on I was having trouble with some fwrite code. I've progressed a little from there, but now I'm stuck again.
In the code below, I'm trying to write data to a binary file, and then read the file and display the data again.
Code:
#include <stdio.h>
#include <math.h>
#define MAXLEN 20
#define FLEETMAX 5
/*Define general struct for dates*/
typedef struct
{
int day;
int month;
int year;
}Dates;
/*Define struct for cars*/
typedef struct
{
char carmake[MAXLEN];
Dates manufactureDate;
Dates purchaseDate;
double purchasePrice;
}Cars;
int writeBinary(Cars *car);
int readBinary(Cars *car);
int main()
{
int i, j, menu;
Cars fleet[FLEETMAX];
Cars temp[FLEETMAX];
i = 0;
while(menu != 6){
scanf("%d", &menu);
switch(menu)
{
case 1:
addCar(&fleet[i]); /*Code which gets input from user via scanf*/
i++;
break;
/*...Some other cases...*/
case 4: /*Save entered cars into a binary file*/
printf("\nSaving to file...\n");
for(j=0; j<i; j++)
{
writeBinary(&fleet[j]);
}
break;
case 5: /*Load fleet from existing binary file*/
printf("\nReading saved file...\n");
for(j=0; j<i; j++)
{
printf("Read loop count: %d\n", j);
readBinary(&temp[j]);
}
break;
}
}
/*Function to write all cars in current fleet to binary file*/
int writeBinary(Cars *car)
{
int i;
FILE *binaryp;
binaryp = fopen("test.bin", "wb"); /*Open binary file for read/write*/
if (binaryp == NULL)
{
printf("Error. Could not open file.\n");
return (1);
}
fwrite(&car, sizeof(Cars), 1, binaryp);
fclose(binaryp);
printf("Saved.\n");
return (0);
}
/*Function to read fleet from binary file and load into program*/
int readBinary(Cars *car)
{
FILE *binaryp;
int i;
binaryp = fopen("test.bin", "rb"); /*Open binary file for reading*/
if (binaryp == NULL)
{
printf("Error. Could not open file.\n");
return (1);
}
fread(&car, sizeof(Cars), 1, binaryp);
printf("Carmake: %s\n", (*car).carmake);
printf("Purchase price: $%.2f\n\n", (*car).purchasePrice);
fclose(binaryp);
printf("Read load finished.\n");
return (0);
}
The problem I get is the output is not what it's supposed to be.
For example, when 2 inputs have been saved, the output should read:
Code:
Carmake: Ford
Purchase price: $111.00
Carmake: Nissan
Purchase price: $222.00
Instead however, the actual output is:
Code:
Carmake: Nissan
Purchase price: $222.00
Carmake: Nissan
Purchase price: $222.00
The code seems to only be copying/displaying the last (i.e. second) entered output TWICE and there's no sign of the first input at all. I'm not sure if it's my logic that's wrong, or if I'm incorrectly using my fread and fwrite, or if it's some other problem. I'd greatly appreciate your help as I'm completely stuck.
Many thanks!
-
Your writebinary function is called several times in a loop. The first instruction in your function is "completely destroy the previous contents of the file". Naturally you end up with no other cars in your file.
-
Wow. I don't believe I missed that! Thanks very much!