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?