I am trying to read data from a text file with some data in it.
My text file:
1 dior Asfiya 20 abcde 12345
2 abde Sabah 17 saar 5757657
My code:
typedef long long int ulong;
struct Customer
{
char name[25];
int acc_no;
int age;
char gender[2];
char address[60];
ulong phone;
char password[10];
};
struct Customer add,check;
int new_acc()
{
int c;
FILE *p;
FILE *q;
p = fopen("test.txt","a");
q = fopen("test.txt","r");
if(p == NULL)
{
puts("Could't open file\n");
return(-1);
}
if(q == NULL)
{
puts("Couldn't open file\n");
return(-1);
}
account_no:
printf("\nAdd record");
printf("\nEnter account number: ");
scanf("%d",&check.acc_no);
while(c = fscanf(q,"%d %s %s %d %s %s %llu%[^\n]",&add.acc_no,add.password,add.name,&add.age,add.gender,add.address,&add.phone) == 7)
{
if(check.acc_no==add.acc_no)
{
printf("\nAccount no. already in use!");
goto account_no;
}
}
if(c != EOF){
goto details;
}
details:
add.acc_no = check.acc_no;
printf("\nEnter password: ");
scanf("%s",add.password);
printf("\nFull Name: ");
scanf("%s",add.name);
printf("\nEnter your age: ");
scanf("%d",&add.age);
printf("\nEnter your gender: ");
scanf(" %c",&add.gender);
printf("\nEnter address: ");
scanf("%s",add.address);
printf("\nEnter phone number: ");
scanf("%llu",&add.phone);
fprintf(p,"%d %s %s %d %s %s %lld\n",add.acc_no,add.password,add.name,add.age,add.gender,add.address,add.phone);
fclose(p);
fclose(q);
}
While debugging the code it gives segmentation fault when the while loop starts. It worked perfectly fine before adding the first line of data into the file. I am not able to figure out why is this happening.