Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ How to assign ifstream content (from file) to string with offset (istreambuf_iterator)

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

like image 612
Admiral Hemut Avatar asked Oct 26 '17 13:10

Admiral Hemut


1 Answers

Sorry, but this isn't generally possible.

The standard only defines two circumstances under which istreambuf_iterators will compare equal to each other:

  1. Immediately after constructing two iterators from the same stream, and
  2. when they're both end-of-stream iterators.

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 what streambuf 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.

like image 105
Jerry Coffin Avatar answered Sep 28 '22 15:09

Jerry Coffin