【问题标题】:How to correctly use fread() to read in specified length of content (C language)如何正确使用 fread() 读取指定长度的内容(C语言)
【发布时间】: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(&amp;num_elements, 1, 1, filePtr); 应该是fread(&amp;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


【解决方案1】:

我想我已经找到了segmentation fault错误的原因:我没有为指针data分配内存

执行 malloc 后分段错误错误消失:data = malloc(size); 在此行之前 fread(data, size, 1, filePtr);

在for循环结束时,我还需要通过free(data);释放分配的内存

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-05-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-20
    • 1970-01-01
    • 2018-10-11
    相关资源
    最近更新 更多