Search code examples
cfwrite

Why does fwrite (with struct) writes unknown symbols?


I want to write a struct to the txt file with fwrite function. When I run my program I see a lot of undefined symbols in the txt file. Why does it happen and how can I fix it? My code:

FILE *file = NULL;

file = fopen(TASK1_2_FILENAME, "wb");

if (!file) {
    printf("FATAL: File does not exist, exiting.");
    exit(EXIT_FAILURE);
}

Products product;
strcpy(product.date, "00:00:0000");
product.code = 12345;
product.quantity = 10;
product.price = 10.5;

fwrite(&product, sizeof(Products), 1, file);

fclose(file);

And the structure in headers file:

typedef struct Product {
    char date[11];
    int code;
    int quantity;
    float price;
} Products;

The result:

enter image description here


Solution

  • You can't write binary data and expect it to be text. The behavior you're seeing is normal, expected, and correct.

    As an example, think of the number 30000. This will easily fit inside a two-byte short int. However, in text format you have at least five bytes. If you fwrite() two bytes to external storage, it will be two bytes containing the numerical value of those bytes, not a text representation of each digit.

    In the example of 30000 the binary representation is 01110101 00110000. This is reversed in Intel machines because they are little-endian. That means those two bytes in your file are probably decimal 48 and 118. If you view those as characters on a PC that used ASCII natively, they should show up as 0 and v, respectively.