Extra Loop with EOF [duplicate] - c

This question already has answers here:
Why is “while( !feof(file) )” always wrong?
(5 answers)
Closed 9 years ago.
I have a problem using the function feof, this is my code:
while(!feof(archlog))
{ if(!fgets(line,MAXLINE,archlog))
printf("\nERROR: Can't read on: %s\n", ARCHTXT);
else
printf("%s",line);
}
When I run this, it prints the text of the file but makes an extra loop and prints the ERROR, I want to avoid this, I want it to only print the text of the file without the extra loop.

The loop will enter once more if the file ends with a new line.
A warkaround whould be:
while(!feof(archlog))
{ if(!fgets(line,MAXLINE,archlog))
printf("\nERROR: Can't read on: %s\n", ARCHTXT);
else
printf("%s",line);
if ( (c=fgetc(archlog)) == EOF)
break;
ungetc(c, archlog);
}

The EOF flag is set once your gets function reads the EOF. This means that the last iteration will always trigger the error message. After this, the loop tests for the EOF flag again, which was triggered on the last read and thus exits the loop.
You could get around this by placing the EOF test inside the loop. There you can either print the text on a successful read or set a boolean to exit the loop if there is a failure.

I always reverse the two function calls:
while(fgets(line,MAXLINE,archlog))
{ if(feof(archlog))
break;
else
printf("%s",line);
}
That gets me out when the end of file is read. Sometimes I 'or' in ferror(archlog) to the feof() call, to break out on error or EOF.

You should not use feof(FILE *f) in your loops as it returns true only if EOF is read, not reached, see How to use feof(FILE *f)?
Instead use fgets and its return code for the condition:
while(fgets(line, MAXLINE, archlog) != NULL) {
printf("%s", line);
}
There is no need for checking feof(archlog) inside the loop. For error checking use ferror(archlog).

Related

EOF reading last line twice

I am pretty new to C and have a very simple function for displaying file contents here. It works fine, except the last line of my file prints twice...I know that it has to do w/EOF but I can't figure out how to get the function to recognize EOF as the last line and not run once more. I know there are a billion places on the internet with similar issues, but lots were for C++ and since I am new I thought it would be best to just use my own code. Here is the code:
{
int count=0, fileEnd=0;
FILE* rockPtr=fopen("rockact.txt", "r");
printf("\n%8s%8s%8s%8s%8s\n", "BANDID", "NAME", "SIZE", "CREW", "TRANS");
do
{
fileEnd=fscanf(rockPtr, "%d%s%d%d%s", &(tempBand.rockid), tempBand.bandname, &(tempBand.bandsize), &(tempBand.crewsize), tempBand.transport);
if (fileEnd !=EOF); //checks EOF has not been reached
{
printf("\n%8d%8s%8d%8d%8s", tempBand.rockid, tempBand.bandname, tempBand.bandsize, tempBand.crewsize, tempBand.transport);
count++;
}
}
while (fileEnd !=EOF);
fclose(rockPtr);
printf("\n The total amount of rock acts on file is %d\n", count);
}
Your if condition doesn't want the semi-colon:
if (fileEnd !=EOF); // This semicolon is wrong!
The semicolon is a null statement and is the body of the if.
I'd rather see the whole loop cast as a while loop:
while (fscanf(rockPtr, "%d%s%d%d%s", &tempBand.rockid, tempBand.bandname,
&tempBand.bandsize, &tempBand.crewsize, tempBand.transport)) == 5)
{
printf("\n%8d%8s%8d%8d%8s", tempBand.rockid, tempBand.bandname,
tempBand.bandsize, tempBand.crewsize, tempBand.transport);
count++;
}
If you want to worry about it, you can spot the difference between EOF, read error and format error after the loop. Note that the check is that all values were converted OK.
you have ; after if - remove it
also, check manual for fscanf
If a reading error happens or the end-of-file is reached while
reading, the proper indicator is set (feof or ferror). And, if either
happens before any data could be successfully read, EOF is returned.
This mean that you can read at least partial data from file, reach EOF or error, but fscanf will not return it.
You should use feof function to check whether end of file is reached
so your logic should be:
read from file
if anything is read - display it, here I mean you should compare returned number with count of arguments, not with EOF
check for feof
UPDATE: during opening/reading from file you should always check ferror, as EOF is not the only problem

feof() on Linux return true at one line later than the ending line [duplicate]

This question already has answers here:
Why is “while( !feof(file) )” always wrong?
(5 answers)
Closed 9 years ago.
I'm a beginner of C. When I use this while loop to print the contains of a file. The last line will print twice on Linux. It should not get into while loop when reach the end of file. It has no problem on windows.
#include <stdio.h>
#include <unistd.h>
int main()
{
char string[400];
FILE *file_para;
// Open the file
if ((file_para = fopen("Test.txt", "r")) == NULL)
{
printf("cannot open file\n");
getchar();
return 0;
}
while (!feof(file_para))
{
fgets(string, 400, file_para);
printf("**** %s", string);
}
fclose(file_para);
getchar();
return 0;
}
This is the wrong way to use feof(). Use feof() to detect what went wrong after one of the main I/O functions failed. It does not predict whether you're about to reach EOF; it tells you when some I/O function has already reported EOF. C is not Pascal; in Pascal, you can (must?) check for EOF before calling the I/O functions.
while (fgets(string, sizeof(string), file_para) != 0)
{
...do printing, etc...
}
// If you need to, use `feof()` and `ferror()` to sort out what went wrong.
If you really, really insist on using feof(), then you also need to check your I/O operation:
while (!feof(file_para))
{
if (fgets(string, sizeof(string), file_para) == 0)
break;
...do printing, etc...
}
Note that you might be failing because ferror(file_para) evaluates to true even when feof(file_para) does not...so maybe you need while (!feof(file_para) && !ferror(file_para)), but that really is just more evidence that the while loop should be conditioned on the I/O function, not feof().
This is a common anti-pattern:
while (!feof(file_para))
{
fgets(string, 400, file_para);
feof() does not detect if the next input call will fail due to end-of-file; it tells you if the file has already reached end-of-file. You should only call it after an input function has already failed, to see why it failed (which could be either an error or end-of-file).
The correct pattern is:
while (fgets(string, 400, file_para))
{

Confusion about file I/O (C)

fwrite(&studentg,sizeof(studentg),1,p);
while(!feof(p))
{
printf("flag");
fread(&studentg,sizeof(studentg),1,p);
printf("%s\t%s\t%s\t%s\t%s\t%s\t\n",studentg.name,studentg.add,studentg.tel,studentg.pc,studentg.qq,studentg.email);
}
Why I put only one object in file,but it output two same line?
And if I put two objects in file,it output one object correct,but another repeated.
I try show feof(p)'s return value,it show me that after fread ,feof(p)'s return value is still 0.Can anyone explain how it happens?
You won't get an end of file until you try to read beyond the file. This means that you have to check eof before the print:
fwrite(&studentg,sizeof(studentg),1,p);
finish = 0;
while(!finish)
{
printf("flag");
fread(&studentg,sizeof(studentg),1,p);
finish = feof(p);
if (!finish)
{
printf("%s\t%s\t%s\t%s\t%s\t%s\t\n",studentg.name,studentg.add,studentg.tel,studentg.pc,studentg.qq,studentg.email);
}
}
or
fwrite(&studentg,sizeof(studentg),1,p);
while(1)
{
printf("flag");
fread(&studentg,sizeof(studentg),1,p);
if (feof(p)) break;
printf("%s\t%s\t%s\t%s\t%s\t%s\t\n",studentg.name,studentg.add,studentg.tel,studentg.pc,studentg.qq,studentg.email);
}
From http://www.cplusplus.com/reference/cstdio/feof/:
"This indicator is generally set by a previous operation on the stream that attempted to read at or past the end-of-file."
This means that end of file is usually detected after an operation.
To fix your code, you may for example replace the condition in while loop with 1 or true and break execution when eof is reached (run feof inside loop).
Use of feof is one of the biggest misconception among beginners in File I/O. Everybody at some point has done the same mistake once or twice.
The way you have used it is Pascal's way but C way is different. The difference is::
Pascal's function returns true if the next read will fail because of end of file.
C's function returns true if the last function failed.
Thats why your code prints the last line twice because after the last line is read in and printed out, feof() will still return 0 (false) and the loop will continue. The next fgets() fails and so the line variable holding the contents of the last line is not changed and is printed out again. After this, feof() will return true (since fgets() failed) and the loop ends.
The correct way to use it is::
while( 1 ) {
fgets(line, sizeof(line), fp);
if ( feof(fp) ) /* check for EOF right after fgets() */
break;
fputs(line, stdout);
}
Still better way::
while( fgets(line, sizeof(line), fp) != NULL )
fputs(line, stdout);
First of all you should include a complete, reproducing, example to what you want to do, not a combined fragment of the code, which is hard to reproduce. Otherwise, note that using fwrite()/fread() on struct contents directly is not portable (see the free online book Porting UNIX Software), and is prone to errors. But you didn't provide enough context for us to understand what went wrong.

While loop never exits for EOF

I'm writing my own shell in C and I need to detect EOF (for when I run ./myshell < commands.txt)
commands.txt contains:
ls
pwd
These both run fine separately from within the program. But when I run it with the text file, I get an infinite loop.
In my while(1) loop for the shell, the first thing I do is this:
if (feof(stdin)) { my_exit(); }
my_exit is simply:
void my_exit() {
printf("End of file! Bye\n");
exit(0);
}
Doesn't exit(0) end the program (and the loop)? Why am I getting
End of File! ByeEnd of File! ByeEnd of File! ByeEnd of File! ByeEnd of File! ByeEnd of File! Bye.... etc
I have also tried doing the fgets == NULL way. Same loop
The problem is that feof() tells you if the LAST input operation ran into EOF. But you're not checking this until the next iteration. So when you're at EOF, you do fgets() and then try to use the empty result that it returned.
What's happening is that you fork() a child process, and then call execvp() with an empty command name. This is failing, so the child process returns to the beginning of the loop, and does the same thing. Meanwhile, the parent process calls my_exit(). So each child process forks another child of its own, and then exits.
The way feof works is that it returns false as long as no read has hit EOF. feof by itself does not check the stream, but checks if EOF indicator has been set, which happens when something like fgets fails.
It really is not a very good practice to use feof in the control loop.
An example of validating EOF can be this:
while( fgets(line, sizeof(line), fp) != NULL )
fputs(line, stdout);
You can try like this...
int a=1;
while(a)
{
if (feof(stdin)) {
a = 0;
}
}
printf("End of file! Bye\n");
exit(0);

Why the fscanf is used 2 times with: while( !feof(File))

why when using fscanf to acquire data from a file, is used 2 times, once before the "!feof(fin)" and later, as shown in the code below:
fscanf(fin, "%s", letta);
while(!feof(fin)){
fscanf(fin, "%s", letta);
}
the word read is not the same?
No the word read would not be the same since you read from the file twice, you would get different data each time.
The condition in the while tests to see if you are at the end of file, in order to do that a read attempt must have been made, which requires the fscanf() before the loop.
Once you are inside the loop you want to continue reading from the file. Presumably there would be more code inside the loop to process the data you are reading.
In the code you have posted, if you encountered the end of file with your first read attempt, you wouldn't enter the (while) loop.
Contrast this with a do-while construct where the test is at the bottom of the loop (ie the read occurs only once, at the "bottom" of the loop). There you will always enter the loop at least once.
There's probably no point in using feof() like this here, yet many people who are (I guess, apologies if I'm mistaken) learning C seem to "want to".
The fact is that fscanf() itself has a return value; if the file ends it will fail to do the requested scanning, and it will tell you so. It will even return the special constant EOF if the file ends. So just loop on the return value of fscanf():
while( fscanf(fin, "%s", letta) == 1 )
{
/* Process, parse, store or do whatever with letta. */
}
Because the EOF flag is only set after a call to fscanf. The condition while(!feof(fin)) doesn't make sense when fscanf hasn't been called yet.
feof doesn't return true until after you try to read past the end of file. Imagine a file like the following:
This is a test$
^
where ^ indicates the current location in the file and $ represents EOF. After the first call to fscanf(fin, "%s", letta);, the stream looks like this:
This is a test$
^
After three iterations of the loop (reading "is", "a", and "test"), you have this:
This is a test$
^
At this point, feof(fin) still returns false, because at this point all you know is that you've reached the end of the string "test". So your loop will execute one more time. Since you're at the end of the file, there's nothing to read, so the contents of letta will not be changed, so it will look like you've read "test" twice. Now feof(fin) will return true.
The moral of the story is that you should not use feof as your loop condition; rather, you should use the result of the read operation itself, like so:
errno = 0;
while (fscanf(fin, "%s", letta) == 1)
{
// process letta
}
if (feof(fin))
{
printf("Reached end of file\n");
}
else
{
perror("Error on read");
}

Resources