writing a C program which opens a text file called phoneList.txt and searches for contacts (firstname, lastname, phonenumber), and updates an existing contact's phone number. My issue is in the update phone number program. When I use fgets to find a matching name to update the contact, the cursor is positioned at the start of the next line, aka at the start of the contact AFTER the contact that matches the user's search. Heres my code:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
int main(void){
struct record{
char firstName[20];
char lastName[20];
char phoneNum[15];
};
struct record info;
FILE *fp;
char line[100];
char phoneInfo[100];
char fullName[100];
char *stream;
int n = atoi(getenv("CONTENT_LENGTH"));
fgets(stream, n+1, stdin); //put query string into stream from stdin
//SET HTML OUTPUT AND TITLE, TEST CONTENT OF STREAM
printf("%s%c%c\n", "Content-type:text/html;charset=iso-8859-1",13,10);
printf("<p>%s</p>", stream);
sscanf(stream, "firstName=%[^&]&lastName=%[^&]&phoneNum=%s", info.firstName, info.lastName, info.phoneNum);
strcpy(fullName, info.firstName);
strcat(fullName, " ");
strcat(fullName, info.lastName);
strcpy(phoneInfo, fullName);
strcat(phoneInfo, " ");
strcat(phoneInfo, info.phoneNum);
//strcat(phoneInfo, "\n");
printf("%s", phoneInfo);
printf("\n");
//TEST FORMATTING OF PHONE INFO VAR
fp = fopen("phoneList.txt", "r+");
if(fp == NULL){
printf("Error opening the file.\n");
return 1;
}
while(fgets(line, 99, fp)!=NULL){
if(strstr(line, fullName)!= NULL){
//fseek(fp, -(strlen(phoneInfo)+1), SEEK_CUR);
fputs(phoneInfo, fp);
printf("Success! Number updated. \n");
fclose(fp);
return;
}
}
if(feof(fp)){
//fputs(phoneInfo, fp);
printf("goes to here");
}
fclose(fp);
return 0;
}
I have fseek commented as it behaves strangely depending on if the contact being searched is at the end of the list. I think it has something to do with the text file having a \n char in it. Wondering if there is a better way to simply overwrite the line which matches the user's search, or at least reset the cursor to the start of the line that matches the search. Ive done a bunch of google searching and searches on this site but I couldnt turn up anything that I understood how to implement. Really appreciate your help! Cheers