Reputation: 1700
After debugging a program for a while, I realize that there is some problem with the function fgets() in C:
example code:
....
char arr[50];
File* file=fopen("mytext.txt","r");
for(int i=0;i<=100;++i){
....
fgets(arr,sizeof(arr),file); //I use a for loop here for example
.... //just to illustrate that I use the
...do some stuff... //fgets() function lots of times
}
fgets(arr,sizeof(arr),file); //And now I use it again but get nothing
//because I have used the fgets() to consume the file up
....
So you see, What I want to say here is :when you use fgets() to get data from the file too many time , it will reach the end of the file. And then when you use it again, it will return nothing (just a null pointer but no error!!)
I discover that problem after debugging for a while. And I have notice that there is also the same problem with the other formattd-input function like scanf().
So I wonder whether there is a method to flush the machine and make thing new so that I can use the fgets() function again. Thanks.
Upvotes: 1
Views: 473
Reputation: 19874
What you are using is a file pointer, fgets() keeps running until it reaches the EOF. So when there is nothing to be read it returns NULL indicating EOF. So in order to get to the beginning of the file you need to use
rewind(file);
and use fgets() to read again the problem is not with the fgets() its with your understanding that during file access the file pointer keeps moving .
Upvotes: 4