Search code examples
c++iteratorfilestream

Copy a part of a file to another using iterators


I'm still practicing C++ and I have issues with char iterators over filestreams.

I want to copy a part of a file to another (temporary) file. I want to find a particular string in the first file (I used std::find algorithm), in order to know where I can "cut" the part of the file to be copied (hope that makes sense). My problem is that with the following code I have a compilation error that I don't really understand.

The part of my code in question looks like this:

ifstream readStream(fileName.c_str());
istreambuf_iterator<char> fStart(readStream);
istreambuf_iterator<char> fEnd;
auto position = find(fStart, fEnd, refToReplace); // refToReplace is a std::string
if (position != fEnd){ // If the reference appears in the file
    ofstream tempStream("temp.fsr"); // create the temp file
    copy(fStart, position , ostreambuf_iterator<char>(fluxTemp)); // and copy the part I want (before the matching string)
}
else{
            continue;
}

And the compilation error I'm getting in "stl_algo.h":

error: no match for 'operator==' in '__first.std::istreambuf_iterator<_CharT, _Traits>::operator*<char, std::char_traits<char> >() == __val'

Thank you in advance.


Solution

  • The compilation error should come with an instantiation backtrace that tells you which call you made ultimately caused the error.

    In your case, this will point at the find call. find looks for a single element, and the element type of your iterators is a single character, but you pass a string. (Based on your description. Your snippet doesn't actually tell us what the type of refToReplace is.)

    The algorithm you're looking for is search, but that requires forward iterators, which streambuf iterators are not.

    You will need to choose a different approach.