<snip>
- in
checkSize, rather than increasing accumulator by sizeof(dummy), then dividing by sizeof(dummy), just write accumulator++, and return accumulator. Same effect, less code. But you'll need to apply a fix to checkSize, see below for the explanation.
- the first thing I checked was printing from an empty file. It produced 1 record of garbage. You should always check assumptions first, before adding any data. This made it clear that "prints a junk record" was not actually related to
storing a new record. Fixing the "empty file prints garbage" bug might fix the other garbage-printing incidents.
- the cause is partly the use of do ... while. "do" always executes once, even if it should fail. That is because the check is always applied at the end of the loop. So it's a bad choice for things which could happen
zero times. e.g. only use do while for things which
must happen at least once. Use normal while for things which might happen no times depending on their condition.
- The main cause is because eof only gets set to true once a read fails. This is no problem for text files if you readline, then the last line triggers eof. But for binary files, you need to read the end of file markers for your read function to alert the system that the file is depleted. So if you have an exact number of records in a binary file, then the last record can be read without triggering the "end of file" detection.
-
the fix is that file.read returns a bool depending on whether it could successfully read any data or not. Knowing that, you can just make a while loop where the condition is your file.read function itself, instead of checking for eof at all. Get this working in
void displayRecords(const char filename[]) and you can roll the same fix out in all the other functions which read records.
- btw, use do / while sparingly. It only makes sense for things where you
have to run the loop once before checking what happened, e.g. for generating random x,y coordinates until they satisfy some condition.