简体   繁体   English

从包含其他结构的二进制文件中写入和读取结构(C)

[英]Writing and reading structs from binary file that contain other structs (C)

I have to write/read from a binary file some structs that I created, but when reading them back in, I get some nasty errors. 我必须从二进制文件中写入/读取我创建的某些结构,但是当回读它们时,会遇到一些讨厌的错误。

Take for example this construction: 以这种构造为例:

typedef struct items
{
    char name[21], power[21];
    int stock;
    double price;
} ITEMS;

typedef struct shop
{
    char name[21];
    int numOfItems;
    ITEMS *arr;
} SHOP;

And now, I can create an array of SHOP and fill everything as is (creating an dynamic array for ITEM, for each SHOP[i]), but I'm not sure if: 现在,我可以创建一个SHOP数组并按原样填充所有内容(为每个SHOP [i]为ITEM创建一个动态数组),但是我不确定是否:

fwrite(); fwrite(); actually writes the whole array, with all the info that is filled in for the ITEM's and when i use fread() it gives some access violation error. 实际上写了整个数组,并为ITEM填写了所有信息,当我使用fread()时,它给出了一些访问冲突错误。

What would be the correct approach, aside from using .txt files for I/O. 除了将.txt文件用于I / O,什么是正确的方法。

Here is a code sample: http://pastebin.com/79TtvQ9t 这是一个代码示例: http : //pastebin.com/79TtvQ9t

If you want to write structure, it should not have the pointer feilds. 如果要编写结构,则不应包含指针字段。 In this cases you should not write by structure. 在这种情况下,您不应该按结构编写。 Because it write an address only for a pointer field 因为它只为指针字段写入地址

The problem is that you're writing the pointer to the file, that should end in something like this 问题是您正在编写指向文件的指针,该指针应以类似以下的结尾

21 chars -> coming from the char array "name" from struct shop 21个字符->来自struct shop的字符数组“名称”

4 bytes -> coming from int numOfItems 4个字节->来自int numOfItems

4 bytes -> coming from the pointer to arr 4个字节->来自指向arr的指针

so, your struct should become something like this 所以,你的结构应该变成这样

typedef struct shop
{
    char name[21];
    int numOfItems;
    ITEMS arr;
} SHOP;

that would end having something similar to this in the file 最终在文件中会有与此类似的东西

21 chars -> coming from the char array "name" from struct shop 21个字符->来自struct shop的字符数组“名称”

4 bytes -> coming from int numOfItems 4个字节->来自int numOfItems

21 chars -> coming from the char array "name" from struct items 21个字符->来自结构项的字符数组“名称”

21 chars -> coming from the char array "power" from struct items 21个字符->来自结构项的字符数组“ power”

4 bytes -> coming from int stock 4字节->来自int库存

8 bytes -> coming from double price 8字节->来自双倍价格

The bytes may vary depending on the PC that you're running your app (in some PCs int has 2 bytes, in others 4, etc.) 字节可能会有所不同,具体取决于您运行应用程序的PC(在某些PC中,int有2个字节,在其他PC中是4个字节,等等)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM