I completed a test today that didn't go so well. The last question dealt with binary files. For the review, he told us we had to go over seekg, tellg, and read and write methods.

On the test there was a class that could find a record (with a record number) using methods to search a binary file.

The problem asked us to write a method:
bool Class_name::find_a_record(ifstream& is, string name)
{
}

The class had a private variable: char m_name[25];

I couldn't figure out how to write a method to search for the record with a string name in a binary file! Any help? I put down trash for my answer. Something with is.seekg((char*)Class, sizeof(&variable)) or something like that in some if statement with EOF. I was working on this with 10 min to spare. UGH. The UML diagram took too long. And I still can't figure out what the answer could be. Any takers? I don't get my test back till Monday and it's killing me.

Edited 7 Years Ago by ihatestarch: n/a

Pretty simple, really

bool Class_name::find_a_record(ifstream& is, string name)
{
     Class_name n;
     is.seekg(0, ios::begin); // start at beginning of the file
     // while not end-of-file or error
     while( is.read( (char*)&n, sizeof(Class_name) )
     {
            if( name == n.name) // if found
            {
                  return true;
            }
     }
     return false;
}

Thank you. I understand the code and it looks so easy, but I'm not sure I had enough practice manipulating the methods seekg/tellg and read/write. I knew how they worked, but I never put them in practice (nor did our homework had us put them into intuitive practice). I feel so demoralized. The whole class was in an uproar about this problem, lol.

Pretty simple, really

bool Class_name::find_a_record(ifstream& is, string name)
{
     Class_name n;
     is.seekg(0, ios::begin); // start at beginning of the file
     // while not end-of-file or error
     while( is.read( (char*)&n, sizeof(Class_name) )
     {
            if( name == n.name) // if found
            {
                  return true;
            }
     }
     return false;
}
This question has already been answered. Start a new discussion instead.