c - 将结构体写入文件中,C

标签 c file

我需要编写一个程序来将一些片段保存在文件中,然后在打开它时加载到程序中。 我的结构是:

struct agenda {
    int idContacte;
    char nom[50];
    struct agenda *segContacte;
};
struct agenda *pAgenda;
struct agenda *pPrimer = NULL;
struct agenda *pIndex;

我通过这种方式将数据获取到我的程序:

while (fread(pAgenda, sizeof(struct agenda), 1, f) > 0){
            pAgenda = (struct agenda *)malloc(sizeof(struct agenda));
            printf("%d", pAgenda->idContacte);
            printf("%s", pAgenda->nom);
}

我这样保存到文件:

pIndex = pPrimer;
    while(pIndex){
        fwrite(pIndex, sizeof(struct agenda), 1, f);
        fclose(f);
        pIndex = pIndex->segContacte;
}

问题是当我打开程序时,如果文件中保存了结构,则程序会发生冲突。我不需要将 *segContacte 保存在文件上,我认为这就是问题所在。 当我在文件中保存一个 id 为 6 且名称为 Albert 的结构时,文件的结果是这样的(我用二进制选项打开文件):

Albert T_CHECK=NO HOMEDRIVE=C: HOMEPATH=\Users\Alber

最佳答案

您的问题在于阅读代码。您在为其分配内存之前正在使用 pAgenda。

while (fread(pAgenda, sizeof(struct agenda), 1, f) > 0){ 
            pAgenda = (struct agenda *)malloc(sizeof(struct agenda));
            printf("%d", pAgenda->idContacte);
            printf("%s", pAgenda->nom);
}

上面的代码应该是这样的

do { 
   pAgenda = (struct agenda *)malloc(sizeof(struct agenda));
   printf("%d", pAgenda->idContacte);
   printf("%s", pAgenda->nom);
} while (fread(pAgenda, sizeof(struct agenda), 1, f) > 0);

关于c - 将结构体写入文件中,C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23803302/

相关文章:

java - 将多个图像保存在一个文件中

python - 当我想从 python 文件中打印列表时,为什么只显示最后一项?

c - 调用函数时出现段错误

c - C 数组中的段错误,访问字符串中的单个字符

使用 libssh 复制文件

Java PrintWriter - 将文件保存到 NetBeans 中的源包

c - 如何将文本文件的一部分复制到C中的字符串中?

c - 当我在我的程序中选择某个选项时,我不断得到一个无限循环

c - 运算符 '++' 的未经允许的操作数 [MISRA 2012 规则 10.1,必需]

java - 压缩子目录仅压缩子目录的内容而不压缩子目录