Help with Reading and writing binary data
I have the following code which reads and writes binary data:
Code:
#include <stdio.h>
typedef struct foo_struct
{
int a;
int b;
int *c;
} foo;
int main()
{
foo *test = (foo *) malloc(sizeof(foo));
FILE *file = fopen("bin.dat", "w");
int i;
test->a = 5;
test->b = 2;
test->c = (int *) malloc(sizeof(int) * 4);
test->c[0] = 7778;
test->c[1] = 88887;
test->c[2] = 9877;
test->c[3] = 178870;
fwrite(test, sizeof(foo), 1, file);
fclose(file);
free(test->c);
free(test);
test = (foo *) malloc(sizeof(foo));
file = fopen("bin.dat", "r");
fread(test, sizeof(foo), 1, file);
printf("a: %i\n", test->a);
printf("b: %i\n", test->b);
for(i = 0; i < 4; i++)
printf("c[%i]: %i\n", i, test->c[i]);
fclose(file);
return 0;
}
This runs fine, but I'm not convinced this works. Do I have to allocate memory for test->c before the call to fread()? If so, how would I read in binary data if c was an indeterminate length? Is there something similar to Java's serialization?
Thanks,
Yasir