I’m trying to understand how to properly right data to a binary file. The data is being written but when read back in for testing it is obvious I am not writing it properly. The data is read/written as follows.
Unsigned Char tells how long next string will be, then a string is written, and then an integer ID is written. ( or length studentname student_id ). The following is the printList function which saves the data to a file.
void printList(struct node * nptr, string filename){
ofstream myfile;
myfile.open( filename.c_str(), ios::binary );
while(nptr){
myfile.write( (char*) &nptr->data.len, sizeof( unsigned char ) );
myfile.write( (char*) nptr->data.name, len * sizeof(char) );
myfile.write( (char*) &nptr->data.id, sizeof(int) );
//myfile.write( (const char*) &nptr->data, sizeof( Student ) );
nptr = nptr->next;
}
myfile.close();
}
Here is the student struct from which the data is stored in a link list:
struct node{
Student data;
struct node* next;
};
//=== Student struct===//
struct Student{
unsigned char len;
char* name;
int id;
};
//====================//
Here is the loadbin file I wrote to read the binary back in, again I am messing something up and I have read and watched a ton of tutorials on this. I really am stumped.
unsigned char len;
char* name;
int id;
int main( int argc, char* argv[] )
{
if( argc > 1 )
{
ifstream f( argv[1] , ios::binary);
while( !f.eof() )
{
f.read( (char*) &len , sizeof( unsigned char ) );
if( f.eof() )
break;
name = new char[len+1];
name[len+1] = '\0';
f.read( (char*) name , len * sizeof( char ) );
f.read( (char*) &id , sizeof( int ) );
cout << (int)len << " " << name << " " << id
<< "\n";
}
}
else
cout << "\nToo few arguments.\n";
}
Some more info, I can’t change how the file is being read back in. The fix has to come from when I’m writing. I just included that in case it would help.
For a start, I’m not even sure this should compile, unless you have a
lenvariable floating around somewhere, such as in your last code segment:Since
sizeof(char)is always one and I prefer explicit expressions as much as possible, I’d rewrite the three output lines as:A full program showing how to use that follows, similar enough that it will help, but different enough so that you can’t just hand it in as your own work 🙂
If you run that program then do a hex dump, you get:
which I think matches the format you wanted.