Forums
New posts
Search forums
Members
Current visitors
Log in
Register
What's new
Search
Search
Search titles only
By:
New posts
Search forums
Menu
Log in
Register
Install the app
Install
Forums
Archive
Archive
C Programming
Printing the last item of a structure twice
JavaScript is disabled. For a better experience, please enable JavaScript in your browser before proceeding.
You are using an out of date browser. It may not display this or other websites correctly.
You should upgrade or use an
alternative browser
.
Reply to thread
Message
[QUOTE="jameskuyper, post: 3910471"] Hoping is nice. But hoping that you have enough money to support your family doesn't actually give you any money, and hoping that your C++ problem isn't off topic in a C newsgroup doesn't remove any of the numerous uses of C++ features from your program. Your actual problem is with the part of the C standard library that is inherited by C++ from C, and is exactly the same problem in both languages, but to expect C programmers to wade though so much C++ stuff in order to figure this out is more than you can reasonably hope for. Next time, post such questions to comp.lang.c++. .... When a file is newly opened, feof(fp) won't be true, not even if it's a zero-length file, so there's no point in testing it until after the first call to fread(). If the call to fread() sets the end-of-file flag, the best you can hope for is that no data was read into your structure. This appears to be what happened in your case; you processed the results of the last fread() call, the one that tried and failed to read the next record when there were no more records to read. The structure happened to still have the same values in it from the previous read, which is why it printed out one more time. You shouldn't count on the consequences of such a mistake being so minor. The worst that can happen is that the structure is only partially filled, or filled in with random contents, in which case any attempt to use it could backfire. Therefore, you should always check for failure immediately after reading data, and process the data which was read in only if the read was successful. A better approach: while(fread(&teu, sizeof teu, 1, fp) == 1) { // process data } if(ferr(fp)) { // error handling } // else { end of file was reached } [/QUOTE]
Verification
Post reply
Forums
Archive
Archive
C Programming
Printing the last item of a structure twice
Top