【发布时间】:2016-11-20 11:41:35
【问题描述】:
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);
}
}
如何使用 fread 读取二进制文件?谁能检查我使用 fwrite 是否正确?我希望我的 read_back 方法打印结构中的内容(标题、年份等)。
【问题讨论】:
-
在您的
read_back函数中,您必须使用malloc函数为每条记录分配内存空间。顺便说一句,您可能应该使用“w”(写入)而不是“a”(附加)来打开 fopen。此外,在某些环境(例如 Windows)上,您需要在 fopen 中使用“rb”和“wb”而不是“r”和“w”来处理二进制文件。