C ++ How to assign ifstream content (from a file) to a line with an offset (istreambuf_iterator)

I am trying to read parts of the contents of a binary in a string. Why line? 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 start to finish. I would like to read only parts in a given position. For example, start at position 10 byte:

 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 offset? I did not find any example. I know there are examples with ifstream.read () in buffers. I used assignment in the string method throughout my program and would really like to find a way to do this with an offset.

Can anyone help me? thanks

+5
source share
1 answer

Sorry, but this is not possible at all.

The standard defines only two circumstances under which istreambuf_iterator will compare with each other:

  • Immediately after creating two iterators from one stream and
  • when they are both end stream iterators.

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 the end of the stream, or neither of them is at the end of the stream, regardless of which streambuf object it uses.

So, for any pair of iterators, they will compare unequal if one is at the end of the stream, and the other is not and the end of the stream. For all other cases (both at the end of the stream and at the end of the stream) they will compare equal (even if, for example, they are not even obtained from one stream).

It’s not entirely clear to me that this requires behavior, but it explicitly allows behavior, and is not just allowed as a random case with a triangle that happened by chance, but as a clearly documented, assumed behavior.

+2
source

Source: https://habr.com/ru/post/1272919/


All Articles