| | |
End of file function
Please support our C advertiser: Programming Forums - DaniWeb Sister Site
![]() |
>My program is reading the last line of data from an infile twice.
I'll bet my next paycheck that your file processing loop looks like this:
Or this:
The problem with that is feof (or stream.eof ) only returns true after an attempt has been made to read from the file and end-of-file was encountered. So your loop will iterate once more than you want, and because the input request failed you will use the last successfully read line. The result is that the last line of the file is processed twice.
The solution is to use the return value of your input function as the loop condition:
Or
As an alternative, you can use an infinite loop and use feof or stream.eof in an if statement immediately after your input functions read from the file. That way you can break from the loop before processing the last line twice.
I'll bet my next paycheck that your file processing loop looks like this:
C Syntax (Toggle Plain Text)
while ( !feof ( in ) ) { /* Read from the file and process */ }
C Syntax (Toggle Plain Text)
while ( !in.eof() ) { // Read from the file and process }
The solution is to use the return value of your input function as the loop condition:
C Syntax (Toggle Plain Text)
while ( fgets ( line, sizeof line, in ) != NULL ) { /* Process and print */ }
C Syntax (Toggle Plain Text)
while ( getline ( in, line ) ) { // Process and print }
I'm here to prove you wrong.
![]() |
Similar Threads
- End of file function + Array (C++)
- no newline at end of file error (C++)
- C++ complete binary tree using an array. Unexpected end file (C++)
- help in using End-OF-File function (C)
Other Threads in the C Forum
- Previous Thread: Estimate value of e
- Next Thread: Linux: gotoxy()
| Thread Tools | Search this Thread |
adobe ansi api array arrays asterisks binarysearch calculate centimeter char convert copyimagefile copypdffile cprogramme creafecopyofanytypeoffileinc createcopyoffile csyntax directory dynamic fflush file fork forloop frequency getlasterror givemetehcodez graphics gtkgcurlcompiling hacking hardware highest homework i/o inches incrementoperators infiniteloop initialization interest kernel km linked linkedlist linux linuxsegmentationfault list lists locate logical_drives match matrix microsoft motherboard multi mysql number open opendocumentformat opensource owf pattern pdf performance pointer pointers posix power problem probleminc program programming pyramidusingturboccodes radix read recursion recv repetition research scanf scheduling scripting segmentationfault send sequential shape socketprograming stack standard string strings structures systemcall testautomation turboc unix user variable voidmain() wab win32api windows.h






