Reading/Writing/Modifying a struct in C

Posted by user1016401 on Stack Overflow See other posts from Stack Overflow or by user1016401
Published on 2012-10-27T04:04:48Z Indexed on 2012/10/27 5:02 UTC
Read the original article Hit count: 124

Filed under:
|

I am taking some information from a user (name, address, contact number) and store it in a struct. I then store this in a file which is opened in "r+" mode. I try reading it line by line and see if the entry I am trying to enter already exists, in which case I exit. Otherwise I append this entry at the end of the file. The problem is that when I open the file in "r+" mode, it gives me Segmentation fault!

Here is the code:

struct cust{
    char *frstnam;
    char *lastnam;
    char *cntact;
    char *add;
};

Now consider this function. I am passing a struct of information in this function. Its job is to check if this struct already exists else append it to end of file.

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);
}

© Stack Overflow or respective owner

Related posts about c

    Related posts about struct