我从用户那里获取一些信息(姓名、地址、联系电话)并将其存储在一个结构中。然后我将其存储在以“r+”模式打开的文件中。我尝试逐行阅读它,看看我尝试输入的条目是否已经存在,在这种情况下我退出。否则,我将此条目附加到文件的末尾。问题是当我以“r+”模式打开文件时,它给了我分段错误!
这是代码:
struct cust{
char *frstnam;
char *lastnam;
char *cntact;
char *add;
};
现在考虑这个函数。我在这个函数中传递了一个信息结构。它的工作是检查该结构是否已经存在,否则将其附加到文件末尾。
void check(struct cust c)
{
struct cust cpy;
FILE *f;
f=fopen("Customer.txt","r+");
int num=0;
if (f!= NULL){
while (!feof(f)) {
num++;
fread(&cpy,sizeof(struct cust),1,f);
if ((cpy.frstnam==c.frstnam)&(cpy.lastnam==c.lastnam)&(cpy.cntact==c.cntact)&(cpy.add==c.add))
{
printf("Hi %s %s. Nice to meet you again. You live at %s and your contact number is %s\n", cpy.frstnam,cpy.lastnam,cpy.add,cpy.cntact);
return;
}
}
fwrite(&c,sizeof(struct cust),1,f);
fclose (f);
}
printf("number of lines read is %d\n",num);
}