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");
}
Related
it is always printing an extra character at the end. here is the code:
#include <stdio.h>
int main ()
{
char bit;
FILE *fp_read,*fp_write;
fp_read = fopen("test.txt","r");
if(fp_read==NULL) {
printf("Error!! Unable to open the file!!");
return 1;
}
while(!feof(fp_read)) {
fscanf(fp_read,"%c",&bit);
printf("%c",bit);
}
fclose(fp_read);
return 0;
}
if test.txt contains 010101 it prints 0101011 . if 00110 it prints 001100. if it contains abc it prints abcc . that means it always repeats the last character.
What is the problem ? can anybody explain ?
I am not able to reproduce the error.
Refer to David Bowling's first comment in the original post for a neat explanation.
The cppreference page for feof has a shorter version.
The eof function only reports the stream state as reported by the most recent I/O operation, it does not examine the associated data source. For example, if the most recent I/O was a fgetc, which returned the last byte of a file, feof returns zero. The next fgetc fails and changes the stream state to end-of-file. Only then feof returns non-zero.
In typical usage, input stream processing stops on any error; feof and ferror are then used to distinguish between different error conditions.
This means that the use of feof in the while loop may not be appropriate. The last character from the file may be junk and will be different in different systems.
Try doing this instead.
while(fscanf(fp_read,"%c",&bit) != EOF) {
printf("%c",bit);
}
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
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.
void echoFileA(const char* iPath,const char* oPath)
{
FILE* iFile;
FILE* oFile;
iFile = fopen(iPath,"rb");
oFile = fopen(oPath,"wb");
while(iFile)
fputc(fgetc(iFile),oFile);
fclose(iFile);
fclose(oFile);
}
The procedure was written purely for fun, I know that there are covenient , premade functions for copying files in the every OS API libriaries. Back to the topic- why the loop condition is always true, even if the EOF was reached a long time ago?
I've checked that I've passed the correct parameters to this function in the testing program.
The body of your loop ...
fputc(fgetc(iFile),oFile);
... does nothing to change the condition of the loop, so it will run forever.
Instead try something like ...
int c;
while((c = fgetc(iFile)) != EOF)
fputc(c, oFile);
The loop will end once you hit the end of the input file.
The condition is not being ignored. iFile is a pointer and since this pointer is never NULL (or rather 0) the while condition is always true.
Try something like:
while(!feof(iFile))
fputc(fgetc(iFile),oFile);
To make the while loop continue until the end of the file has been reached.
iFile is just a pointer to the file. It does not change anymore after you call fopen. As a condition in the loop you need to use, for instance, the return value from fgetc, since that will tell you whether you have reached the end of the file.
I don't know exactly why a file pointer reads an extra line from a file, specifically the last line, here is the code:
FILE *fp ;
fp = fopen ("mac_ip.txt", "r") ;
int mac;
char *ip = (char *) malloc(15);
while(!feof(fp)){
fscanf(fp,"%i",&mac);
fscanf(fp,"%s",ip);
printf("MAC: %i\n",mac);
printf("IP: %s\n",ip);
}
and the file has exactly 20 lines, but the line 20, is printed twice.
Which is the error?
Thanks in advance.
Because after reading the last two values, you still haven't hit EOF. So the loop goes on. In the next pass of the loop, fscanf actually does not read the last line for the second time like it appears, the fscanfs fail, but the printfs print out the values from the previous pass of the loop.
feof does not "know" it's at the end of file until you try to read some more. Since fscanf tells you how many items it got, you can use this simple trick:
for(;;){
if (fscanf(fp,"%i%s", &mac, ip) != 2) break;
printf("MAC: %i\n",mac);
printf("IP: %s\n",ip);
}
After you have done the two reads on the twentieth line, you have got to the end of the file but the system doesn't know this. feof will only trigger when you try to get past the end of the file, not when you are exactly on it ...
Also, you may have a line-end (CR or CR-LF) on the 20th line which it will only get past with another attempted read.
The solution is to read the line in one go (there is a specific C command for this) and then parse that to get your data. If the whole-line read fails, then you've got to the end.
Your code resembles to the following example
#include <stdio.h>
int main(void)
{
char buffer[256];
FILE * myfile;
myfile = fopen("some.txt","r");
while (!feof(myfile))
{
fgets(buffer,256,myfile);
printf("%s",buffer);
}
fclose(myfile);
return 0;
}
from
http://www.friedspace.com/feof.html
You better test for fscanf return value before printing result. I bet that in the last iteration of your loop, fscanf calls fail and you print the last returned results.
FILE *fp ;
int mac;
char ip[15];
fp = fopen ("mac_ip.txt", "r") ;
if (!fp) return;
while(1){
if (fscanf(fp,"%i",&mac) < 1) break;
if (fscanf(fp,"%s",ip) < 1) break;
printf("MAC: %i\n",mac);
printf("IP: %s\n",ip);
}
fclose (fp);
fscanf() returns the number of assignments it mad (or -1 on eof). By using the return value, you don't need the eof() function. BTW I don't think you can read a MAC address into an int. Maybe you need to read that into a string, too ?
Explanation: feof() does not do what the OP expects. feof() should only be inspected after one of the file operations failed. In most cases you don't need feof().