3

I've got a problem when i try to write data to a binary file. This is the code:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>

typedef struct
{
char name[255];
int quantity;
float price;
} product;

int main()
{
product x;
FILE *f;
strcpy(x.name,"test");
x.quantity=10;
x.price=20.0;
f=fopen("test.txt","wb");
fwrite(&x,sizeof(x),1,f);
fclose(f);
return 0;
}

When I run the program,it only writes the x.name string,ignoring the other 2(quantity and price). I've googled it and this seems to be the correct function to write data to a binary file...but it still doesn't work for me. What should I do? Thanks in advance!

flaviumanica
  • 195
  • 1
  • 4
  • 14

2 Answers2

3

Your function works fine, the problem is that you write a lot of unused data, are not using the right tool to view your binary file.

You put "test" into the name, which has a size of 255 characters. This uses up the first five (four letters plus null terminator) while the remaining 250 characters are unused. They are written to the file, and their content become "junk filling" between "test" and the other data.

If you write a simple program to read your file back, you would discover that both the quantity and the price are set correctly to the values that you wrote:

int main()
{
    product x;
    FILE *f;
    f=fopen("test.txt","rb");
    fread(&x,sizeof(x),1,f);
    fclose(f);
    printf("'%s' - %d %f\n", x.name, x.quantity, x.price);
    return 0;
}
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
  • The "test" string was just an example. In reality,I've got an array which has longer names. However,I tried to ignore the string and write to the file only the quantity and it shows me a blank file. If I try to print the quantity in the console,it shows the correct value... – flaviumanica Jan 17 '15 at 13:40
  • 2
    @flaviumanica That's probably because you are opening a binary file with a text editor. In this case, numbers written as binary do not look right - they appear as "junk characters" or get interpreted as an end-of-line markers by text editors. – Sergey Kalinichenko Jan 17 '15 at 13:43
1

According to your code you are trying to write address of x. But if you want to write full object then you have to serialize the object first.