An Overflowed Stack An Overflowed Stack - 14 days ago 7
C Question

How could I read a binary file using fread?

typedef struct
{
char*title;
char* year;
char* length; //in minutes
} record;

void write(record* list[])
{
FILE* out=fopen("output.bin","a");
if(!out)
{
printf("error"); exit(1);
}else
{
int i;
for (i = 0; i < 1024; i++)
{
if(list[i]!=NULL)
fwrite(list[i], sizeof(record), 1, out);
}
fclose(out);
}
}
void read_back()
{
FILE* input=fopen("output.bin","r");
if(!input)
{
printf("error"); exit(1);
}else
{
record* temp[1024];
fread(temp,sizeof(record)*1024,1,input);


fclose(input);
}

}


How could I read the binary file using fread? Could anyone check if I did correct using fwrite? I want my read_back method to print the content in a struct (title, year etc).

Answer

record struct elements are defined as pointers. fread cannot assign those pointers implicitly. For every element in the record struct, the values should be read explicitly and related values should be assigned after memory allocation through malloc.

fwrite will only write memory addresses in this way into the memory, since what record struct has only pointers inside.

There are two options

Define static array definitions like below

 typedef struct
{
    char title[256];
    char year[4];
    char length[8]; //in minutes
} record;

or

write record structure elements one by one by with their references.

Comments