c - 如何从二进制文件写入和读取动态数组

标签 c struct binaryfiles dynamic-arrays

我有这个结构

    struct _recipe
{
    char name[50];
    char** ingredients;
    char diff[12];
    int time;
    int calories;
    char** procedure;   
} recipe;

我想复制二进制文件中的所有数据。 首先,我已经为成分和过程动态分配了内存,并且我已经编写了我需要的所有内容。但随后我需要将所有内容写入二进制文件。我知道它们都是指针,所以这意味着如果我使用

fwrite(&recipe,sizeof(recipe),1,fbr);

我将在文件中写入地址,而不是我需要的实际值。我尝试以这种方式在文件中写入结构的每个字段

    fwrite(recipe.name,sizeof(recipe.name),1,fbr);

    fgets(recipe.ingredients[j],30,stdin);
            strcpy(buff,recipe.ingredients[j]);
            len = strlen(buff);
            fwrite(buff,sizeof(recipe.ingredients[0]),len,fbr);

   fwrite(recipe.diff,sizeof(recipe.diff),1,fbr);
   fwrite(&recipe.time,sizeof(recipe.time),1,fbr);
   fwrite(&recipe.calories,sizeof(recipe.calories),1,fbr);

    fgets(recipe.procedure[i],1000,stdin);
            strcpy(buff,recipe.procedure[i]);
            len = strlen(buff);
            fwrite(buff,sizeof(recipe.procedure[0]),len,fbr);

我不确定这是否正确,但我尝试将字符串放入另一个字符串中,然后将其复制到文件中。问题是,我不确定它是否有效,因为我不知道应该输入什么样的命令来读取我存储的所有值。当然,它的名称有效,我对此没有任何问题,但当我准备阅读成分时,我阻止了自己,因为我将值写在另一个字符串中,我不知道应该输入多长的内容阅读。也许我遗漏了一些东西,也许我一开始就在写东西,但我现在不知道该怎么办。

最佳答案

你想做这样的事情来写出你的食谱:

    fwrite(recipe.name,sizeof(recipe.name),1,fbr);
    for (int i = 0; i < num_ingredients; i++) {
            int len = strlen(recipe.ingredients[i]) + 1;
            int num_elements = fwrite(recipe.ingredients[i],sizeof(char),len,fbr);
            printf("wrote %d elements for %s\n", num_elements, recipe.ingredients[i]);
    }
    fwrite(recipe.diff,sizeof(recipe.diff),1,fbr);
    for (int i = 0; i < num_procedures; i++) {
            int len = strlen(recipe.procedure[i]) + 1;
            int num_elements = fwrite(recipe.procedure[i],sizeof(char),len,fbr);
            printf("wrote %d elements for %s\n", num_elements, recipe.procedure[i]);
    }

当然,您还需要写出卡路里和时间。在将任何内容读入结构之前我也会这样做:

memset(&recipe, 0, sizeof(struct _recipe));

如果您使用 fprintf 以 \n 作为分隔符写出卡路里和时间,您的食谱文件将如下所示:

$ od -c recipe.bin
0000000   m   u   f   f   i   n   s  \0  \0  \0  \0  \0  \0  \0  \0  \0
0000020  \0  \0  \0  \0  \0  \0  \0  \0  \0  \0  \0  \0  \0  \0  \0  \0
*
0000060  \0  \0   f   l   o   u   r  \0   s   u   g   a   r  \0   e   g
0000100   g   s  \0   v   a   n   i   l   l   a  \0   n   u   t   s  \0
0000120   n   o       d   i   f   f  \0  \0  \0  \0  \0   m   i   x  \0
0000140   b   a   k   e  \0   r   e   s   t  \0   6   0  \n   2   5   0
0000160  \n

关于c - 如何从二进制文件写入和读取动态数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51196138/

相关文章:

c - 根据面积对n个三角形的边进行排序

C++ 覆盖父结构中的数据不起作用

C++ 二进制文件方法正在从文件中删除内容?

serialization - 使用 MapReduce 读取/写入二进制输入/输出文件的最佳方式是什么?

java - 使用相对路径保存我的二进制文件找不到路径

c - 通过函数参数添加到 main 中的数组

c - AMD xop 检查支持

c - 如何在 C 中使用 GDI+?

c - 在推出自己的结构时提供辅助功能

c# - 检索结构体的 [StructLayout] 属性