Please help me, I made a function to modify a line in file using C language. Now my problem is that although the line is modified, the rest of the line I modified is still as is; For example if the new data I enter is shorter than the original line, my new data will be written, but the rest of the line will still be filled with old data. Please check the first line in the outputs below. Please advise me, thank you very much.
Original file:
Sam,Thomas,10-06-1995,26 Elhoreya Street,01234567899,sthomas@gmail.com
Steven,Thomas,10-06-1995,26 Elhoreya Street,01234567899,sthomas@gmail.com
Expected output file:
John,George,12-1-2000,23 MN Street,1234567899,gJoh@gmail.com
Steven,Thomas,10-06-1995,26 Elhoreya Street,01234567899,sthomas@gmail.com
Real output file:
John,George,12-1-2000,23 MN Street,1234567899,gJoh@gmail.com@gmail.com
Steven,Thomas,10-06-1995,26 Elhoreya Street,01234567899,sthomas@gmail.com
This is my function:
void modify(contact c[])
{
int flag=0, k=0, count_matches=0, match_cont_pos[100], choose;
char name[50], temp;
FILE * file;
file = fopen("info.txt", "rb+");
if(file == NULL)
{
printf("Error opening file\n");
exit(1);
}
else
{
printf("\nEnter the name you want to search: ");
scanf("%s",&name);
for(int j = 0; name[j] != '\0'; j++)
name[j] = tolower(name[j]);
for(int i = 0; i < count ; i++) {
for(int j = 0; c[i].last_name[j] != '\0'; j++)
c[i].last_name[j] = tolower(c[i].last_name[j]);
if(strcmp(c[i].last_name,name) == 0)
{
match_cont_pos[k]=i;
k++;
}
}
for(int d=0;d<k;d++)
printf("match pos %d\n",match_cont_pos[d]);
for(int d=0;d<k;d++){
printf("\n%s\n%s\n%d %d %d\n%s\n%d\n%s\n\n", c[match_cont_pos[d]].last_name,c[match_cont_pos[d]].first_name,c[match_cont_pos[d]].DoB.day,c[match_cont_pos[d]].DoB.month,c[match_cont_pos[d]].DoB.year,c[match_cont_pos[d]].street_address,c[match_cont_pos[d]].phone_number,c[match_cont_pos[d]].email);
}
if(k>1){
printf("Enter the number of the record you want to modify: ");
scanf("%d",choose);
printf("Enter last name: ");
scanf("%s",&c[match_cont_pos[choose-1]].last_name);
printf("Enter first name: ");
scanf("%s",&c[match_cont_pos[choose-1]].first_name);
printf("Enter phone number: ");
scanf("%d",&c[match_cont_pos[choose-1]].phone_number);
printf("Enter email: ");
scanf("%s",&c[match_cont_pos[choose-1]].email);
printf("Enter birth date: ");
scanf("%d %d %d",&c[match_cont_pos[choose-1]].DoB.day,&c[match_cont_pos[choose-1]].DoB.month,&c[match_cont_pos[choose-1]].DoB.year);
printf("Enter the address: ");
scanf("%c",&temp); // temp statement to clear buffer
scanf("%[^\n]",&c[match_cont_pos[choose-1]].street_address);
fseek(file,-sizeof(c),SEEK_SET);
fprintf(file,"%s,%s,%d-%d-%d,%s,%d,%s",c[match_cont_pos[choose-1]].last_name,c[match_cont_pos[choose-1]].first_name,c[match_cont_pos[choose-1]].DoB.day,c[match_cont_pos[choose-1]].DoB.month,c[match_cont_pos[choose-1]].DoB.year,c[match_cont_pos[choose-1]].street_address,c[match_cont_pos[choose-1]].phone_number,c[match_cont_pos[choose-1]].email);
}
}
fclose(file);
}