Why did I have to use freopen in this case?

0

I have the following code:

#include <stdio.h>

int main(void){

    FILE *ptr_file;

    ptr_file=fopen("archive.txt", "r");

    short size=0;
    char c;

    while(!feof(ptr_file)){

        c=getc(ptr_file);

        if(c=='\n'){

            size++;
        }
    }

    ptr_file=freopen("archive.txt", "r", ptr_file);

    printf("Size=%d\n\n", size);

    while(!feof(ptr_file)){

        c=getc(ptr_file);

        if(c=='\n'){

            size--;
        }
    }

    printf("Size=%d\n\n", size);

    fclose(ptr_file);

    return 0;
}

Basically this code has the function of reading the file until its end ( EOF ) counting the number of lines and soon after reading the file again until its end, however this time decrementing the variable that indicates the number of lines rows in the previous loop . Ok, where do I want to go with this? Note that if I take out the freopen function the code does not work as expected, the second loop does not run, but now why does it not spin? Why is it necessary to use the freopen function in this situation?

    
asked by anonymous 10.04.2018 / 02:30

1 answer

1

The problem is that you already have the file open because it made fopen at the top:

ptr_file=fopen("archive.txt", "r");

As you read from the file, you move the current position to the end. Once at the end, to re-read from the beginning you need to reposition at the beginning. One way to do this is fseek :

fseek ( ptr_file , 0 , SEEK_SET );

Where SEEK_SET indicates positioning from the start, and 0 would be the number of bytes to go from the beginning.

Another way would be to close and reopen the file. In the latter case you have two alternatives:

  • fclose followed by a new fopen
  • freopen that was the option you used, and turns out to be the most direct when it comes to closing and opening

Answering the question now:

  

Note that if I take the freopen function the code does not work as the   expected, simply the second loop does not spin

Do not run because the position is already at the end, so there is nothing left to read. freopen makes it position again at startup.

    
10.04.2018 / 03:56