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:

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

Notice there are four 2-byte entries not just three. So either the format is incorrect or you didn't post the correct file contents.

how you read the text might be something like this:

char text[255] = {0};
myfile.read(text, msglen);
text[msglen] = 0; // null-terminate the string

Notice there are four 2-byte entries not just three. So either the format is incorrect or you didn't post the correct file contents.

how you read the text might be something like this:

char text[255] = {0};
myfile.read(text, msglen);
text[msglen] = 0; // null-terminate the string

Thanks for the suggestion , will try it.

The format is not wrong, notice the endianess too.

So when these are read 02 00 becomes 0002, etc.

02 00  (1st 2 bytes is total number of entries, it doesn't appear again)
01 00 3C 00 18 00Welcome home dear friend 
02 00 3C 00 07 00Go Away

Problem solved, thanks a lot

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.