Umit Ulusoy
Umit Ulusoy

Reputation: 65

Reading and searching datas from binary file

in my lab work we gotta read datas from txt and write them to .dat file as a binary format, then we should search and find datas by given id in binary file. Our worker.txt file in this

format:

ID firstname lastname age salary

like:

341 Alex Morgan 32 3400
234 Jessica Gibson 28 2000
...

Program reads these datas then writes all of them to worker.dat as a binary file.

The problem is when entered valid Id for searching program find and print it but then close with windows stopped execution error, I need your help to handle it.

My searchByID function:

void searchByID( int key )
{
bool find=false;
int id,age,sal;
string fn,ln;
ifstream InFile;
InFile.open("worker.dat", ios::in | ios::binary);
int i = getSize( initialArr );
int j;
for( j=0; j<i; j++ ){
    InFile.read( (char*)&id, sizeof(int));
    InFile.read( (char*)&fn, sizeof(string));
    InFile.read( (char*)&ln, sizeof(string));
    InFile.read( (char*)&age, sizeof(int));
    InFile.read( (char*)&sal, sizeof(int));
    if( id == key )
    {
        cout << "Datas for Entered ID:\n"
            << id <<" "<< fn <<" "
            << ln <<" "<< age <<" "
            << sal << endl;
        find = true;
    }
}
if( !find )
    cout << "Entered ID not Found on File" << endl;
InFile.close();
}

Upvotes: 2

Views: 1967

Answers (2)

Hogan
Hogan

Reputation: 70513

There seems to be a number of problems here, as I said in the comments you are describing the format of worker.txt and reading from a file called worker.dat. Are they the same format? If not then you are reading a text file. If so then you don't know the length of the strings -- but I would guess they are null terminated.

Here is an example of one of your problems -- sizeof(string) will always be the size of the pointer not the length of the string you are reading.

If this is a text file what you want to do is this:

  • Read a line from the text file.

  • Parse that line

Upvotes: 1

Vaughn Cato
Vaughn Cato

Reputation: 64308

Doing something like this isn't going to work:

InFile.read( (char*)&fn, sizeof(string));

A string usually internally contains a pointer to the actual characters, so the actual text wouldn't be stored in the file anywhere. You would need to use a char array to read and write your strings instead.

Upvotes: 2

Related Questions