Hi guys,
I'm trying to write a small program which will search a file for few bytes and replace it with another bunch of bytes. But everytime I try running this small app I got message about istream_iterator is not dereferenceable. I'm even not sure that I know how exactly iterator works, this is a new subject for me.

Here is relevant parts:

#include "stdafx.h"
#include <fstream>
#include <iterator>
#include <algorithm>

using namespace std;

int main() {

    typedef istream_iterator<char> input_iter_t;
    typedef ostream_iterator<char> output_iter_t;

    const off_t SIZE = 4;
    char before[SIZE] = { 0x12, 0x34, 0x56, 0x78 };
    char after[SIZE] = { 0x69, 0x74, 0x65, 0x72 };

    fstream filestream("numbers.exe", ios::binary | ios::in | ios::out);
    if (search(input_iter_t(filestream), input_iter_t(), before, before + SIZE) != input_iter_t()) {
    filestream.seekp(-SIZE, ios::cur);
    filestream.write(after, SIZE);
    }
    
    return 0;
}

Cheers,
Flybro

If you know polish, see my reply on the problem at http://forum.4programmers.net/viewtopic.php?p=584934

In short: on msvc istream_iterator doesn't work well with fstream. problem is with copying iterators: they do not preserve past state of the stream. create an iterator A, copy it and have two identical iterators A and B. push B forward for 5 times, then push and re-read A - you will get 5, 6 or 7 element, don't remember now.

THIS IS NOT TRUE FOR ALL ITERATORS.
This is true for this specific iterator+stream combination.

It's an ugly implementation detail.
istream_iterator simply uses operator >> on the underlying stream and caches read values not to duplicate read on multiple dereferences. This behaviour directly annihilates the very basic idea of copying this iterator.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.