在文件中写入结构,C
我需要做一个程序,以保存在一个文件中的一些Strats,然后加载到程序时,我打开它。 我的结构是:在文件中写入结构,C,c,file,C,File,我需要做一个程序,以保存在一个文件中的一些Strats,然后加载到程序时,我打开它。 我的结构是: struct agenda { int idContacte; char nom[50]; struct agenda *segContacte; }; struct agenda *pAgenda; struct agenda *pPrimer = NULL; struct agenda *pIndex; 我通过以下方式将数据输入程序: while (fread(pAg
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;
}
我通过以下方式保存到文件:
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;
}
问题是当我打开程序时,如果文件中保存了结构,程序会发生冲突。我不需要在文件中保存*segcontact,我认为这就是问题所在。
当我在文件中保存一个id为6且文件名为Albert te resutl的结构时,是这样的(我打开文件whit binary选项):
Albert T\u CHECK=NO HOMEDRIVE=C:HOMEPATH=\Users\Alber
首先读取pAgenda
指向的位置(这是第一次迭代时的随机值),然后为其分配内存
反过来做。这是:首先将内存分配给
pAgenda
,然后读取到它指向的位置。从文件中读取数据时,您的代码应该如下所示
while(1)
{
pAgenda = (struct agenda *)malloc(sizeof(struct agenda));
if(fread(pAgenda, sizeof(struct agenda), 1, f)==0)
break;
printf("%d", pAgenda->idContacte);
printf("%s", pAgenda->nom);
}
------------------------------------如果SEGContact不需要存储到文件中,您的代码可以如下所示(用于写入文件) 相应地,您应该从文件中分两部分读取每条记录
if(fread(&pIndex->idContacte, sizeof(int), 1, f)==0)
break;
fread(pIndex->nom,50,1,f);
您的问题在于读取代码。在为代码分配内存之前,您正在使用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);
阿尔克说的。还要注意,再次读取下一个指针后,它很可能无效。您应该只保存原始数据id和名称,并考虑一种从文件创建链表的方法。但仍在文件中保存某些内容,但在读取时,程序不会获取任何数据。如果文件中有内容,程序将转到第一个If:
If(fread(pAgenda,sizeof(struct agenda),1,f)==0)break然后不要读文件。我想是因为它保存错误。文件中总是我插入的名称,然后是我的硬盘中的随机rute,如下所示:`Albert T_CHECK=NO HOMEDRIVE=C:HOMEPATH=\Users\Alber`文件中的“某物”是垃圾数据,因为我们使用fwrite(pIndex->nom,50,1,f)存储50字节的数据代码>假设pIndex->nom在其50字节的位置(结构中的nom[50])保存一个字符串“hello”,我们当然会存储44个垃圾字符。在50个字符中,5个是“hello”,1个是“\0”,其余44个是未知(垃圾)字符。如果我们不希望该数据存储在文件中,请确保在将实际数据放入数组nom之前,数组在50个位置包含“\0”(NULL)字符。