fread storing value incorrectly?

Viewed 59

I have a binary file, that when I fread I store the value, I then fwrite the same value to a new binary file, but the value that is stored is different to the one I read.

When I print the value its correct? So im unsure as to why the written value is different.

I've written up a basic view of the relavent code I have.

#include<stdio.h>
#include<stdlib.h>
struct Data
{
  char phone;
  long long int cheese;
  double chicken;
}

int main(){

FILE *data_input;
FILE *output_file;
int array_size=10;

data_input=fopen("input.bin","rb");
output_file=fopen("output.bin","wb");

struct Data *input_array;
input_array=malloc(sizeof(struct Data)*array_size);

fread(&input_array->phone, sizeof(input_array->phone), 1, data_input);
fread(&input_array->cheese, sizeof(input_array->cheese), 1, data_input);
fread(&input_array->chicken, sizeof(input_array->chicken, 1, data_input);

printf("%i, %llx, %f \n", input_array->phone, input_array->cheese, input_array->chicken);

flcose(data_input);
free(input_array);

fwrite(&intput_array->phone, sizeof(input_array->phone), 1, output_file);
fwrite(&intput_array->cheese, sizeof(input_array->cheese), 1, output_file);
fwrite(&intput_array->chicken, sizeof(input_array->chicken), 1, output_file);

fclose(output_file);
return 0;
}

The printf results are:

0, bd6130, -6.351429

when I use od -t x1 input.bin the bytes are:

00 30 61 bd 00 00 00 00 00 00 00 00 00 dd 67 19 c0

when I use od -t x1 output.bin the bytes are:

00 10 a0 72 fb 3b 56 00 00 00 00 00 00 dd 67 19 c0

I don't understand why the byte values are different, for the value of cheese.

1 Answers

Do not free input_array until you make sure it is no longer used.

BTW, there are some typos.

struct Data
{
  char phone;
  long long int cheese;
  double chicken;
};

int main(){

FILE *data_input;
FILE *output_file;
int array_size=10;

data_input=fopen("input.bin","rb");
output_file=fopen("output.bin","wb");

struct Data *input_array;
input_array=malloc(sizeof(struct Data)*array_size);

fread(&input_array->phone, sizeof(input_array->phone), 1, data_input);
fread(&input_array->cheese, sizeof(input_array->cheese), 1, data_input);
fread(&input_array->chicken, sizeof(input_array->chicken), 1, data_input);

printf("%i, %llx, %f \n", input_array->phone, input_array->cheese, input_array->chicken);

fclose(data_input);

fwrite(&input_array->phone, sizeof(input_array->phone), 1, output_file);
fwrite(&input_array->cheese, sizeof(input_array->cheese), 1, output_file);
fwrite(&input_array->chicken, sizeof(input_array->chicken), 1, output_file);

fclose(output_file);
free(input_array); // never used again
return 0;
}
Related