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