•
•
•
•
What is DaniWeb IT Discussion Community?
You're currently browsing the C section within the Software Development category of DaniWeb, a massive community of 361,550 software developers, web developers, Internet marketers, and tech gurus who are all enthusiastic about making contacts, networking, and learning from each other. In fact, there are 2,061 IT professionals currently interacting right now! Registration is free, only takes a minute and lets you enjoy all of the interactive features of the site.
Please support our C advertiser:
Views: 2940 | Replies: 2
![]() |
>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:
while ( !feof ( in ) ) {
/* Read from the file and process */
}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:
while ( fgets ( line, sizeof line, in ) != NULL ) {
/* Process and print */
}while ( getline ( in, line ) ) {
// Process and print
} Member of: Beautiful Code Club.
![]() |
•
•
•
•
Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)
•
•
•
•
•
•
•
•
DaniWeb C Marketplace
Similar Threads
- no newline at end of file error (C++)
- warning:no newline at end of file (C)
- ERROR--Unexpected end to file (C++)
- Windows programming - C - Save file function (C++)
- "Input past end of File" error #62 (Legacy and Other Languages)
- 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: c language problm, how to pass pointer to a function
- Next Thread: Can you guys help me? about Quick Sort Algorithm



Linear Mode