我使用 fwrite() 函数将 4 个数据 block 写入名为“example2.bin”的文件中。在文件的开头,我还写了 block 的数量(在这个追逐中是 4)。每个 block 包含以下格式的数据:0(偏移量)、4(字符串大小)和字符串“dang”。
我首先将内存地址复制到char *buffer,其中包含 block 的数量,以及如上所述的4个数据 block 。然后我做了以下事情:
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 value is 4
before the for-loop, position is 4
offset is 0 and position is 8
size is 67108864 and position is 1996488708 Segmentation fault (core dumped)
我不明白为什么大小和位置增加到这么大的数字。感谢您的帮助。
最佳答案
我想我已经找到了段错误错误的原因:我没有为指针data
分配内存
在此行之前执行 malloc: data = malloc(size);
后,段错误错误消失 fread(data, size, 1, filePtr);
在 for 循环结束时,我还需要通过以下方式释放分配的内存:free(data);
关于c - 如何正确使用fread()读取指定长度的内容(C语言),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23095048/