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.
Last edited by Ancient Dragon; Jan 21st, 2007 at 9:03 am.
Sponsor
Team Colleague
Featured Poster
Reputation Points: 5608
Solved Threads: 2282
Retired and Enjoying Life
Online 21,960 posts
since Aug 2005