0

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.

cloud
  • 105
  • 9

1 Answers1

1

you are using return 0 for void readfile() function, remove return 0

I just posted an answer for your previous question, refer it.

search string from file and store it in struct using c

IrAM
  • 1,720
  • 5
  • 18
  • hi, thank you for answering my previous question. :) for this question, i've removed the `return 0` in my void function, but it's still printing out all data. i think the problem lies in my main function. – cloud Oct 19 '20 at 07:07
  • In your main function you opened file in append mode `fPtr = fopen("profile.txt", "a");`, if you are running your program multiple times ( check `profile.txt` once), then same entries will be appended at the end of your file `profile.txt`, better use `fPtr = fopen("profile.txt", "w");` – IrAM Oct 19 '20 at 07:20