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);
}
The problem is that your structure contains pointers to strings and not strings themselves. So freading and fwriting will not work because the pointer values will be read and written but aren’t valid between runs of the application.
A simple fix would be to change the structure to:
It’s not a great fix, but it is a fix and might work for you.