Checking if the file pointer reaches EOF without moving the file pointer?

My question is simple, but I can not find it on google, so I'm here.

Basically, as an example, I read a bunch of integers before EOF from the input file. I used fgetc to check, but then it moves the file pointer to the address of the second integer. How can I check the EOF in this while loop without moving the file pointer while checking it?

Keep in mind that I will do something much more complex with this loop than scanning in integers. Also, I don't know how to use fscanf instead of fgets. This is just a simple example to show you what I mean.

while(fgetc(ifp) != EOF) { fscanf(ifp, "%d", &test); printf("%d\n", test); } 

If the input file has integers 1-10, for example, the above code will print:

2 3 4 5 6 7 8 9 10

Missing 1!

+4
source share
5 answers

fgetc Returns the character pointed to by the pointer to the internal position of the file of the specified stream. The position indicator of the internal file then advances to the next character. Using do{ }while(); will solve your problem.

+7
source

You should consider EOF terms as an implementation detail. What really matters is whether fscanf returned the value successfully.

 while(fscanf(ifp, "%d", &test) == 1) { printf("%d\n", test); } 

On the other hand, this is similar to one of those cases where it makes sense to put logic in the middle of a loop.

 while(1) { int ret = fscanf(ifp, "%d", &test); if (ret != 1) break; printf("%d\n", test); } 

Especially for debugging, it can be nice to split things up into separate instructions with variables that can be checked.

+5
source

For various reasons, it is not possible to determine whether EOF was achieved without actually doing a preliminary read from the file.

However, using a separate function call for this is a bad idea, even if you must use ungetc() to return the character you were trying to read.

Instead, check the return value of the call on fscanf() :

 while(fscanf(ifp, "%d", &test) == 1) { printf("%d\n", test); } 
+3
source

How about just:

 while (fscanf (ifp, "%d", &test) != EOF) printf("%d\n", test); 
+3
source

fgetc(ifp) move the file pointer so skip the first integer

Use instead: -

 while(1) { if(fscanf(ifp, "%d", &test)!=1) break; printf("%d\n", test); } 
+2
source

Source: https://habr.com/ru/post/1495260/


All Articles