【发布时间】:2014-04-15 21:40:32
【问题描述】:
我使用 fwrite() 函数将 4 块数据写入名为“example2.bin”的文件中。在文件的开头,我还写了块的数量(在这个追逐中为 4)。每个块包含以下格式的数据:0(偏移量)、4(字符串大小)和字符串“dang”。
我首先将内存地址复制到 char *buffer 中,其中包含块的数量,以及上面解释的 4 个数据块。然后我做了以下事情:
filePtr = fopen("example2.bin", "wb+");
fwrite(buffer, contentSize, 1, filePtr); /*contentSize is the sum of the 4 blocks in byte */
fwrite() 运行良好,我能够看到保存在文件 example2.bin 中的字符串。但是,我在解析文件 example2.bin 时遇到问题:
int main()
{
FILE *filePtr;
int listLength = 0;
int num_elements = 0;
int position = 0;
int offset = 0;
int size = 0;
char *data;
listLength = fileSize("example2.bin"); /* get the file size in byte */
filePtr = fopen("example2.bin", "rb");
fread(&num_elements, 1, 1, filePtr); /* get the number of blocks saved in this file */
printf("num_elements value is %d \n", num_elements);
position += sizeof(num_elements); /* track the position where the fread() is at */
printf("before the for-loop, position is %d \n", position);
int index;
for (index = 0; index < num_elements; index++)
{
fread(&offset, position, 1, filePtr);
position += sizeof(offset);
printf("offset is %d and position is %d \n", offset, position);
fread(&size, position, 1, filePtr);
position += sizeof(size);
printf("size is %d and position is %d \n", size, position);
fread(data, position, 1, filePtr);
position += size;
printf("size is %d and data is %s \n", size, data);
}
return 0;
}
当我运行编译后的程序时,我得到了以下输出,这对我来说很奇怪:
num_elements 值为 4
在 for 循环之前,位置是 4
偏移量为 0,位置为 8
大小为 67108864,位置为 1996488708 分段错误(核心转储)
我不明白为什么大小和位置会增加到这么大的数字。感谢您的帮助。
【问题讨论】:
-
1)
fread(&num_elements, 1, 1, filePtr);应该是fread(&num_elements, sizeof num_elements, 1, filePtr);(fread(object address, record size, number of record, FILE*)) -
您告诉
fread读取 1 个字节并将该字节存储到num_elements,这是一个 4 字节变量。您要么需要为num_elements写入/读取四个字节,要么将num_elements设置为char并写入/读取一个字节。 -
另外,请阅读
fread的手册页。fread的第二个参数不是你想的那样。fread自动跟踪文件中的位置。 -
建议始终检查来自
fread()的返回值 -
非常感谢,感谢您的回复。
标签: c serialization fwrite fread