Home > database >  How to use EOF as the condition to finish the loop? In C
How to use EOF as the condition to finish the loop? In C

Time:01-11

I'm making somewhat like an othello game. I receive a file that contains strings, and i have to read and process them, making the board as it goes. Example of the file received:

  1. Alejandro,B
  2. Federico,N
  3. B
  4. D6
  5. C4
  6. G5

then i would convert the characters to numbers, so it can fit in the int board[8][8] i use

I was expecting that when it reaches the EOF it would get out of the loop, but instead it never stops the loop and keeps reapeting the last line with the printf. This is in the main function:

while( EOF != 1 && *error != 1)
    {
        tomaJugada(&fp,jugada);  //takes 1 line of the file
        toupper(jugada[0]);      
        int columna = convierte_a_int(jugada[0])-1;  //converts the letter to a number
        int fila =  (jugada[1]-'0')-1;               //converts the char number to int number
        printf("columna %i, fila %i \n",columna, fila);   
    }

This is the auxiliary function:

void tomaJugada(FILE** fp, char jugada[])
{    
    fgets(jugada,5,*fp);
    jugada[2] = '\0';
    //jugada[strcspn(jugada, "\n")] = 0;
}

I have seen people using thi:

int ch = getc(fp);
  while (ch != EOF){...

but it would consumme data that i need to use, maybe i'm using it wrong?

Resumming: i want to use all the data in the file, reach de EOF, and end the loop. How can i put the condition for the EOF?

I hope i explained myself well, i appreciate any help

CodePudding user response:

EOF in c is just a constant (typically -1), EOF != 1 would always evaluate to the same (that is guaranteed to be true as EOF will always be negative). What you need to do is to check if fgets returns null pointer (that is in the tomaJugada function) and when that happens, then either an error occurred or you've reached the end of the file. To disambiguate between the two you could use the feof function for instance.

  • Related