c++iteratorbinaryfilesifstreamistream-iterator

Why doesn't the istreambuf_iterator advance work


I was reading Constructing a vector with istream_iterators which is about reading a complete file contents into a vector of chars. While I want a portion of a file to be loaded in to a vector of chars.

#include <iostream>
#include <fstream>
#include <iterator>
#include <vector>
#include <algorithm>

using namespace std;

int main(int argc, char *argv[])
{
    ifstream ifs(argv[1], ios::binary);
    istreambuf_iterator<char> beginItr(ifs);
    istreambuf_iterator<char> endItr(beginItr);
    advance(endItr, 4);
    vector<char> data(beginItr, endItr);
    for_each(data.cbegin(), data.cend(), [](char ch)
    {
            cout << ch << endl;
    });
}

This doesn't work, since advance doesn't work, while the aforementioned question's accepted answer works. Why doesn't the advance work on istreambuf_iterator?

Also

  endItr++;
  endItr++;
  endItr++;
  endItr++;
  cout << distance(beginItr, endItr) << endl;

returns a 0. Please somebody explain what is going on!


Solution

  • Why doesn't the advance work on istreambuf_iterator?

    It works. It advances the iterator. The problem is that an istreambuf_iterator is an input iterator but not a forward iterator, meaning it is a single pass iterator: once you advance it, you can never access the previous state again. To do what you want you can simply use an old-fashioned for loop that counts to 4.