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).
我怎么能用fread读取二进制文件?任何人都可以检查我是否使用fwrite正确吗?我希望我的read_back方法在结构(标题,年份等)中打印内容。
1 个解决方案
#1
1
record
struct elements are defined as pointer
s. 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
.
记录结构元素被定义为指针。 fread无法隐式分配这些指针。对于记录结构中的每个元素,应显式读取值,并在通过malloc分配内存后分配相关值。
fwrite
will only write memory addresses in this way into the memory, since what record
struct has only pointers inside.
fwrite只会以这种方式将内存地址写入内存,因为什么记录结构只有指针内部。
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.
通过引用逐个编写记录结构元素。
#1
1
record
struct elements are defined as pointer
s. 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
.
记录结构元素被定义为指针。 fread无法隐式分配这些指针。对于记录结构中的每个元素,应显式读取值,并在通过malloc分配内存后分配相关值。
fwrite
will only write memory addresses in this way into the memory, since what record
struct has only pointers inside.
fwrite只会以这种方式将内存地址写入内存,因为什么记录结构只有指针内部。
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.
通过引用逐个编写记录结构元素。