Test end of file in C

Asked

Viewed 175 times

2

Hello, I have a problem and I couldn’t solve.

while(!feof(arquivo)) {
    fscanf(arquivo, "%d[^,]",&result);
    fseek(arquivo,+1,SEEK_CUR);
    printf("%d",result);

    fscanf(arquivo, "%d[^,]",&result);
    fseek(arquivo,+1,SEEK_CUR);
    printf("%d",result);

    fscanf(arquivo, "%d[^,]",&result);
    fseek(arquivo,+1,SEEK_CUR);
    printf("%d",result);

    fscanf(arquivo, "%d[^\n]",&result);
    printf("%d",result);

}

My code should read a text file formatted as follows:

5, 1, 2, 3
4, 3, 1, 8

After making the reading instead of the print result: 51234318 it always prints 512343188888, I thought it could be solved by exchanging while for "do while", but the problem persisted. What I need to modify so that the reading ends at the expected time?

The complete function is this:

void alocaProcesso(FILE *arquivo){
   char *linha;
   char *valor;
   int result;
   if(arquivo == NULL){
       printf("Problemas na leitura do arquivo");
       return;
   }
   while(!feof(arquivo)) {
      fscanf(arquivo, "%d[^,]",&result);
      fseek(arquivo,+1,SEEK_CUR);
      printf("%d",result);

      fscanf(arquivo, "%d[^,]",&result);
      fseek(arquivo,+1,SEEK_CUR);
      printf("%d",result);

      fscanf(arquivo, "%d[^,]",&result);
      fseek(arquivo,+1,SEEK_CUR);
      printf("%d",result);

      fscanf(arquivo, "%d",&result);
      printf("%d",result);

   }
   fclose(arquivo);
}

1 answer

3


The problem is that the reading has not yet hit the end of file (EOF) when the loop goes to the third cycle, and feof() still returns FALSE. Testing EOF right after trying to read the first line number via fscanf():

   while(1) {
      fscanf(arquivo, "%d[^,]",&result);
      if (feof(arquivo)) {
          break;
      }

Browser other questions tagged

You are not signed in. Login or sign up in order to post.