Search code examples
cstringfgets

How to properly look for a string in a file?


In this function, I am displaying a .txt document to the screen, which works, however, I am trying to read the file document and scan the document for the word EMPTY as I have it saved as a string variable. It should be noted that I am counting the time EMPTY is in the file and later printing the times it was would in the file along with on another thing. My first question is am I doing this correct?

 void allSeats(void)
    {
        int position = 0;
        int count = 0;
        char gone[6] = "EMPTY";

        system("cls");
    retry: 
        fseatArrangement = fopen("airlineSeatingArrangment.txt", "r");
        while (fgets(econoAirSeatArrangement, 1000, fseatArrangement) != NULL)
            printf(econoAirSeatArrangement);
        fclose(fseatArrangement);

        while (count < FULL)
        {
            fgets(econoAirSeatArrangement, 1000, fseatArrangement);
            fscanf(fseatArrangement,"%s", &gone);
            count++;
        }
        printf("There are %d seats vacant at the moment\nThere are %d seats with no vacancy at the moment \n",count, FULL-count);


        printf("Enter Zero(0) Key to return to menu at anytime.");
            scanf("%d", &position);
            if (position == 0)
            {
                system("cls");
                menu();
            }
            else
            {
                system("cls");
                printf("INVALID INPUT! Please try again.\n");
                goto retry;
            }

        system("pause");
        return;

    }

Solution

  • The main problem is here

     fgets(econoAirSeatArrangement, 1000, fseatArrangement);
    

    you have already closed the file pointer using fclose(), and yet, you try to use it. It causes undefined behavior.

    That said,

    • printf(econoAirSeatArrangement); appears wrong. If you do not wish to have any format conversion specification you can stick to puts().
    • You must check the return value of fopen(), fgets(), fscanf() etc. for success before using the returned value / scanned value.