我(一如既往)在写入和读取链表时遇到了一些麻烦。
它被保存到二进制文件的事实让我感到困惑。
我尝试编写一个简单的程序,只有一个简单的结构和两个变量,并将其写入和读取到磁盘,只是为了检查我是否误用了 fread()
或 fwrite()
。然而,我不是。程序运行得很顺利。
当我开始将指针和节点添加到链表时,麻烦就开始了。
我检查了 stackoverflow.com、cplusplus.com、cprograming.com,据我所知,我的程序没有任何问题。试过调试,没有。编译器一点也不提示。
我在下面包含的源代码非常简单:包含一个具有两个变量(名称和代码)的结构,如客户端控件。该代码由程序自动给出,用户输入名称。然后程序应该保存数据,并继续运行。但是,它不会通过 fir->sacode = 1
赋值。
任何提示将不胜感激。
#include <stdio.h>
void save(void);
int load(void);
struct solic {
char name[10];
int sacode;
struct solic *next;
};
struct solic *cur, *fir;
int sacode = 1;
int main()
{
if(load() == 0)
printf("Load Successful!\n");
char cho1;
fir->sacode = 1;
cur=fir;
while(1){
cur->sacode = sacode;
printf("Client code is %04d",cur->sacode);
printf("Enter client name: ");
scanf("%s",cur->name);
save();
printf("Saved!\n");
printf("Press '1' to enter another client, or 'Enter' to save and exit.\n");
scanf("%c",&cho1);
if(cho1 == '1')
{
cur->next = (struct solic *)malloc(sizeof(struct solic));
cur = cur->next;
sacode++;
cur->sacode = sacode;
continue;
}
else if(cho1 == '\r');
break;
}
return(0);
}
void save(void)
{
FILE *pFile;
pFile = fopen("db.dat","w");
while(cur != NULL)
{
fwrite(cur->name,sizeof(cur->name),1,pFile);
fwrite(&cur->sacode,sizeof(int),1,pFile);
cur = cur->next;
}
fclose(pFile);
}
int load(void)
{
int size;
char buffer[10];
FILE *pFile;
pFile = fopen("db.dat","r");
if(pFile == NULL)
return(1);
size = fseek(pFile,0,SEEK_END);
rewind(pFile);
cur = fir;
while(size >= ftell(pFile))
{
fread(cur->name,sizeof(cur->name),1,pFile);
fread(buffer,sizeof(int),1,pFile);
cur->sacode = atoi(buffer);
sacode++;
cur->next = (struct solic *)malloc(sizeof(struct solic));
cur = cur->next;
}
cur->next = NULL;
return(0);
}
最佳答案
第一次运行这个程序时,
load()
会失败,因为没有数据。这意味着fir
不会被初始化,所以fir->sacode = 1
会尝试更新内存中的一些随机位置。在fir
中存储任何内容之前,您需要使用malloc()
为其分配一个新节点。save()
函数每次运行时都会写入一个新的db.dat
文件,从cur
指针开始。但每次调用它时,cur
都会指向列表中的最后一个元素。您将需要打开此文件进行追加,这样它就不会写入任何已经存在的数据,或者循环遍历整个列表。
关于c - 写入和读取链表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20547292/