简体   繁体   中英

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

Sorry, but this isn't generally possible.

The standard only defines two circumstances under which istreambuf_iterator s 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM