c - 读/写/修改 C 中的结构

标签 c struct

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

最佳答案

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

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

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

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

关于c - 读/写/修改 C 中的结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13097145/

相关文章:

c++ - char* str ="ab", str 和 &str 的混淆

c - 如何使这个结构体实例在 C 中可变?

c - For循环忽略第一行,在C中第一次循环执行后

c - 为什么 *ptr.member 错误而 (*ptr).member 正确?

C++ 结构构造函数错误

c - strftime 没有使用 %C 选项给出正确的输出 - Solaris 10

c/linux无限循环应用: deallocate memory if kill -9 command is called

c++ - 如何在 Mac OS X 上从命令行进行分析?

go - 具有结构体的结构体指针的接口(interface)的函数赋值显示不同的值

创建新的 tcp 套接字 - 服务器端