0

我从用户那里获取一些信息(姓名、地址、联系电话)并将其存储在一个结构中。然后我将其存储在以“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);
}
4

3 回答 3

4

问题是您的结构包含指向字符串的指针,而不是字符串本身。因此 freading 和 fwriting 将不起作用,因为指针值将被读取和写入,但在应用程序运行之间无效。

一个简单的解决方法是将结构更改为:

struct cust{
char frstnam[25];
char lastnam[25];
char cntact[25];
char add[25];
};

这不是一个很好的修复,但它是一个修复并且可能对你有用。

于 2012-10-27T04:10:36.433 回答
2

此外,以这种方式比较字符串是行不通的——它只是比较指针。

你可能想要更多这样的东西:

if ( strcmp(cpy.frstnam,c.frstnam) == 0 && strcmp(cpy.lastnam,c.lastnam) == 0 ...
{
    printf("Hi ...
    return;
}

这将比较字符串数组的实际内容,而不是指针。

此外,“&”是按位与,“&&”是您想要的逻辑与。

于 2012-10-27T04:16:40.910 回答
0

如果您找到匹配的联系人,您的当前代码将返回而无需先关闭文件。最终,您可能会用完可用的文件描述符,并且对 fopen 的调用将失败。

于 2012-10-27T04:39:51.573 回答