In C file reading: how do execute fgets on a same file multiple times?

Viewed 1767

For example;

I have a while loop that loop through the file

while (fgets(line, MAXLINE-1, filePointer)!=NULL){
// do something;
}
fclose(filePointer);

after the loop finish, if I call fgets on the same file will return me null because fgets already finish the whole file. Then how should I read through the file again if I want to use fgets()?

2 Answers

To reset the file pointer, you may use two approaches:

rewind(fp);

and:

 fseek(fp, 0L, SEEK_SET);

Where fp is the FILE pointer. You may then call fgets() again to read the file from its beginning.

At the end of the while loop what happens is that the file pointer reaches to the end of the file(known as EOF). The OS keeps a record of the position of the pointer to keep track of where you are or what your position is in the file so that it can read further from that position. All you need to do is just move that file pointer to the beginning of the file. Now there are two ways for that you can use the rewind() method or the fseek() method. This is how:

rewind(fp);

OR

fseek(fp, 0, SEEK_SET);

use this before reading the same file again. for the record, fp refers to the file that you are trying to read

Related