i've written the code below
void readfile();
struct profile {
char name[30];
int age, phoneNo;
};
int main()
{
FILE* fPtr;
fPtr = fopen("profile.txt", "a");
printf("\n\nPlease enter your details:");
struct profile c;
printf("\n\nEnter your name: ");
gets(c.name);
printf("\nEnter your age: ");
scanf("%d", &c.age);
printf("\nEnter your phone number: ");
scanf("%d", &c.phoneNo);
fprintf(fPtr, "%s,%dy,%d#\n", c.name, c.age, c.phoneNo);
fclose(fPtr);
readfile();
return 0;
}
the code above accepts data from the user and puts in into a text file called profile.txt, the stored records in the text file looks like this:
James Brown,37y,01123456789#
Mary Ann,45y,0123456749#
i called for the function readfile();
in the main program, but the function doesn't work properly. the code of readfile();
is as belows:
void readfile()
{
char fName[15], line[30];
FILE *f;
f = fopen("profile.txt", "r+");
printf("Enter name: ");
fgets(fName, sizeof(fName), stdin);
while (fgets(line, sizeof(line), f)) {
fName[strcspn(fName, "\n")] = '\0';
if (strstr(line, fName) != NULL) {
printf("%s", line);
}
}
fclose(f);
}
in this function, i want to search for a name and print out the entire string containing the record. but when i execute my code, the code fgets(fName, sizeof(fName), stdin);
seems to be ignored as it doesn't let me enter a name to search. rather, it just prints out ALL of the contents of the file, which defeats the purpose. when i call for this function using a main()
with no other code, it works just fine, so I'm not sure why is it that when i have code in my main()
that the function stops working as usual? i'd appreciate it if someone could point out how i can fix this problem in my code.