Hi, just looking for a quick answer to my problem:
How can I read a string from a binary file?
for example

string buff;
binfile.read(reinterpret_cast<char*>(&buff), 10)

does not work. Doesn't work either if buff is declared as a c-style string.
I'd preferably like to read it into an STL string. Thanks.

Recommended Answers

All 2 Replies

If it doesn't work when using a C-style string, there's obviously something fishy going on in your code. Perhaps you're trying to read from the wrong location. As usual, check that the stream is not in an error state, and check the number of charecters read if an error occured.

But most of all, could you post your code?

Hi, just looking for a quick answer to my problem:
How can I read a string from a binary file?
for example

string buff;
binfile.read(reinterpret_cast<char*>(&buff), 10)

does not work. Doesn't work either if buff is declared as a c-style string.
I'd preferably like to read it into an STL string. Thanks.

Of course it doesn't work -- you are passing a pointer to a c++ object to a function that wants a char*. And you are fooling the compiler into thinking that YOU are correct, which you are not.

char buf[11];
binfile.read(buff, 10) ;
// null-terminate the string.  This assumes that the
// length of the string is known -- 10
buf[10] = 0;
// now create the c++ string object
string str = buf;

You have to know the contents of the binary file for the above to work -- if the file contains variable-length strings then the file must also contain something that indicates the length of the string, such as preceeding the string with its length, or the file contains a null character that indicates the end of the string. Either of these conditions makes your program a little more complex.

The code above should work if the strings are fixed-length strings, in the example the length of the string would always be 10, if shorter than 10 then the string in the file would have to be padded with spaces to force it to 10 characters.

Without knowing more about the contents of the binary file you are working with it is nearly impossible to give you more definitive help.

commented: Good info. -joeprogrammer +5
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.