Reputation: 1613
I currently have a std::stringstream
that contains all the data from a given file. This file contains some text as well as binary data.
In the beginning there is a string name, so I get it this way:
std::string name;
std::getline(stream, name, '\0');
Later on, I need to retrieve the contentLength
. Part where I'm failing:
int32_t contentLength;
stream >> contentLength;
I learned that this won't work, since the stream
>>
operator will try to convert instead of casting my 4 bytes with the literal value of the length
.
I have seen some low level (c
) implementation of how to do that. But I would like you guys to advise me of a more reliable way of doing it.
Upvotes: 1
Views: 232
Reputation: 103761
You can use the read
function to read binary data.
stream.read((char*)&contentLength, sizeof(contentLength));
You just need to be careful if you share this file between computers with different endianness, in which case the bytes might need to be reversed.
Upvotes: 3