Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Wanet Telecoms Ltd on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

feof problems

Status
Not open for further replies.

Guest_imported

New member
Jan 1, 1970
0

regarding the bit of code below, which I posted before and recived help with, Russ also pointed out the following (which I was aware of and had fudged around):


----snip*-----
Also, you have a common error in your loop where you use the feof() function to test for end of file at the top. The problem is that feof() doesn't evaluate the stream passed to it, so it won't detect end of file until the code inside the loop has already detected it, in this case fscanf(). This will cause you to read the value of EOF into your variables, if this conversion is possible.

---snip-----


no amount of messing with while or do whiles can solve this problem properly. Any suggestions.

Thanks

tom






===snip file reading code =====

while(!feof(textfile))

lstptr = (INPUT*) malloc(sizeof(INPUT));
fscanf(textfile,"%s %s %s %s", lstptr->field0, lstptr->field1, lstptr->field2, lstptr>field3);
rcdCtr++;
lstptr->next = endOfInputPtr
endOfInputPtr = lstptr;
} fclose(textfile);
 
Hi change the program like the follwoing

while(1)
{
lstptr = (INPUT*) malloc(sizeof(INPUT));
fscanf(textfile,"%s", lstptr->field0);
if(feof(textfile) break;
fscanf(textfile,"%s", lstptr->field1);
if(feof(textfile) break;
fscanf(textfile,"%s", lstptr->field2);
if(feof(textfile) break;
fscanf(textfile,"%s", lstptr>field3);
if(feof(textfile) break;

rcdCtr++;
lstptr->next = endOfInputPtr
endOfInputPtr = lstptr;
}
fclose(textfile);




 
use the return value from scanf, or else you might
be caught on an infinite loop (if the format is not
suitable to the scanf fmt string):

for (;;) {
lstptr = (INPUT*) malloc(sizeof(INPUT));
if (fscanf(textfile,&quot;%s %s %s %s&quot;, lstptr->field0, lstptr->field1, lstptr->field2, lstptr>field3) <= 0)
break;
rcdCtr++;
lstptr->next = endOfInputPtr
endOfInputPtr = lstptr;
}
fclose(textfile);


cya

--
pkiller
 
A typical way to work around this is to have your file reading function's (fscanf(), fgets() fgetc() etc.) return value as the test for ending the loop:

while (fscanf(...) == number_of_items_to_retrieve) {
/* ... */
}

while (fgets(...)!=NULL) {
/* ... */
}

Then after the loop ends, you can call feof() or (usually better) ferror() to find out if your loop was able to read the whole file:

if (ferror(fp)) {
/* The loop ended because of an error on the file */

OR

if (!feof(fp)) {
/* didn't reach end of file, probably due to
* an error */

Russ
bobbitts@hotmail.com
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top