I'm almost done with my assignment but now I'm stuck with some binary file problems. Below is the binary file section of my work.

cin.ignore();
cout << "\nPlease enter filename: ";
cin >> openBinary;
ifstream finBinary;
finBinary.open(openBinary, ios::in | ios::binary);
if (!finBinary.good())
    cerr << "File could not be opened" << endl;
else
{
    finBinary.read((char*)&students, sizeof(info)*MAX_STUDENTS);
    finBinary.seekg(0, ios::end);
    a = finBinary.tellg();
    cout << a/sizeof(info) << endl;
    for (int q = 0; q < MAX_STUDENTS; q++)
    {
        cout << "ID: " << students[q].ID << endl;
        cout << "Name: " << students[q].name << endl;
        cout << "Address: " << students[q].address << endl;
        cout << "Telephone no.: " << students[q].telephone << endl
        << endl;
    }
}

I can't get my program working when I put !finBinary.eof(). Google'ed and found out that binary files have some characters similiar to eof? So I decided to use the seekg and tellg, which gives me a weird number and not what I was expecting (which is 5 records in the binary file).
Anyone can tell me why?

Edit: I went around the problem by inserting
if (strlen(students[q].ID) == 0)
break;
However, I'm still interested to know how to get the number of records in a binary file :D

>I can't get my program working when I put !finBinary.eof().
Put it where? Why don't you post the code you're asking a question about so we don't have to guess?

>Google'ed and found out that binary files have some characters similiar to eof?
That's a different eof. There's the physical representation (if there even is one on your system) for end-of-file that's stored in the file, and there's the end-of-file flag within standard C++ streams. The latter is what you're trying to use, and it will work properly regardless of the orientation of your stream. Most likely your code is wrong.

>So I decided to use the seekg and tellg, which gives me a weird number
That weird number is most likely the number of bytes in the file (not the number of records, unless a record is one byte), which is what I would expect on most implementations.

>I'm still interested to know how to get the number of records in a binary file
The same way you get the number of records in a text file. The only 100% portable method is to read them all:

Record record;
int n = 0;

while ( next_record ( in, record ) )
  ++n;

Of course, given this knowledge it makes sense that the best solution if you can manage it is to process all of the records as you read them to avoid reading them twice.

This article has been dead for over six months. Start a new discussion instead.