Because in this case I had to use freopen?

Asked

Viewed 85 times

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 then reading the file again until its end, but this time decrementing the variable indicating the number of lines incremented in the loop previous. Ok, where do I go with this? Note that if I take the function freopen the code does not work as expected, just the second loop does not rotate, but now why it does not rotate? Why is it necessary to use the function freopen in that situation?

1 answer

1


The problem is you already have the file open because you did fopen at the top:

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

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

fseek ( ptr_file , 0 , SEEK_SET );

In which SEEK_SET indicates positioning from the start, and the 0 would be the number of bytes advancing from start.

Another way would be to close and open the file again. In this last case you have two alternatives:

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

Now to answer the question:

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

It does not rotate because the position is already at the end, so there is nothing more to read. freopen makes position again at the beginning.

Browser other questions tagged

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