i try to read parts of a binary file content into a string. Why a string? I need this for my message protocol (with protobuf).
The following works very well:
std::string* data = new std::string();
std::ifstream ifs("C:\\data.bin", std::ios::binary);
data->assign((std::istreambuf_iterator<char>(ifs)), (std::istreambuf_iterator<char>()));
But this is for reading the file from the beginning to end. I would like to read only parts at given position. For example begin at position byte 10:
std::string* data = new std::string();
std::ifstream ifs("C:\\data.bin", std::ios::binary);
ifs.seekg((10);
data->assign((std::istreambuf_iterator<char>(ifs)), ???????);
But how to adjust the end or the offset? I did not find any example. I know there are examples with ifstream.read() into buffers. I used the assign into string method in my whole program and would really love to find a way doing this with offset.
Can anyone help me? Thanks
Sorry, but this isn't generally possible.
The standard only defines two circumstances under which istreambuf_iterator
s will compare equal to each other:
Just to give an idea of what this means, consider that the sample code in the standard implements its equal()
as follows (N4659, §[istreambuf.iterator.ops]/5):
Returns:
true
if and only if both iterators are at end-of-stream, or neither is at end-of-stream, regardless of whatstreambuf
object they use.
So, for any pair of iterators they will compare not-equal if one is at end of stream, and the other is not and end of stream. For all other cases (both at end of stream, or neither at end of stream) they will compare equal (even if, for example, they aren't even derived from the same stream).
It's not entirely clear to me that this is required behavior, but it's clearly allowed behavior--and not just allowed as an odd corner case that happened by accident, but as clearly documented, intended behavior.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With