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="Beej Jorgensen, post: 3910485"] Some will likely try to redirect you to a C++ newsgroup, but this is actually a C problem, IMO. I'm going to bet that you've assumed that feof() will return true as soon as you've read up through the last byte of the file. But this is incorrect; feof() is set once you've read /past/ the end of the file. [Though I'm having trouble finding the bits of the standard that spell it out quite so explicitly.] This is a good time to do some desk checking. Let's say your file has just one struct in it, so it should print out one struct, right?. Trace through this one step at a time. 1. EOF? No. 2. Read a record (struct #1) (EOF remains clear at this time because you haven't yet read _past_ the end of the file--you've only read up to the end.) 3. Print a record (struct #1) <<<<<<<<<<<<<< 4. EOF? No. 5. Read a record (fails, returning 0, because you read off the end) (You should check the return value of fread() to make sure it has read the number of items you think it has. In any case, at this point the EOF flag is set because you've read past the end of the file.) 6. Print a record (struct #1, again) <<<<<<<<<<<<<< 7. EOF? Yes So notice that we've printed a record twice even though it's the only record in the file. What you want to do is not print those values again if feof() is true. A couple of relatively clean ways I've seen to do this are: // using the comma operator, read a record, then, for the while() // condition, check the status of feof() while(fread(&teu,sizeof(ender),1,fp), !feof(fp)) { cout<<teu.rua<<"\n"; cout<<teu.n<<"\n"; } or, perhaps more clearly: // print records while fread() returns more than zero items // (in this case you only asked for 1 item, so it should always // return either 0 or 1 items.) while(fread(&teu,sizeof(ender),1,fp) > 0) { cout<<teu.rua<<"\n"; cout<<teu.n<<"\n"; } You can also test for more errors by clearing the error flag before the while() loop with clearerr(), and then testing with ferror() after the while loop. (Or, in the first case, by adding &&!ferror() to the while condition.) -Beej [/QUOTE]
Verification
Post reply
Forums
Archive
Archive
C Programming
Printing the last item of a structure twice
Top