How to read binary file with numbers and text

Hello,

I have a binary file of this format:

1st 2 bytes = total number of entries (This appears only once at the file beginning)

Then each record is of the following format:

2 Bytes = Entry no.
2 Bytes = Entry category
2 Bytes = Description length
n Bytes = Description

for example if someone opens the file with a hex editor here is what he sees:

 
02 00 01 00 3C 00 18 00Welcome home dear friend02 00 3C 00 07 00Go Away


I can read the numbers fine using:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

short int msgnumber;
short int category;
short int msglen;

ifstream myfile;
myfile.open (datfile,ios::in | ios::binary);

while (!myfile.eof() && a < 2)
{
   myfile.read(reinterpret_cast<char*>( &msgnumber ),sizeof(msgnumber));
   myfile.read(reinterpret_cast<char*>( &category ),sizeof(category));
   myfile.read(reinterpret_cast<char*>( &msglen ),sizeof(msglen));
   
   //Read the text somehow????
}


but I can't read the text. Can someone please give me some directions?

Thanks
1
2
char* message = new char[msglen];
myfile.read(message, msglen);

You may also want to add the null char. In that case allocate a longer string and set the last element manualy.
Problem solved, thanks a lot
Topic archived. No new replies allowed.