Search code examples
c++iofstreamistream-iterator

c++ fstream obj rollback after using in istream_iterator


How to reset iterator state or use fstream obj, which was in use by istream_iterator, in other istream_iterator. I tried seekp(ios_base::begin) and clear() methods on fstream obj but this doesn't do any affect.

main(){
    fstream ofs{"219.txt"};
    fstream ofstl{"219-.txt"};

    ofstream rezult{"219-rezult.txt"};

    istream_iterator<string> begf{ofs};
    istream_iterator<string> begs{ofstl};
    istream_iterator<string> end;

    ostream_iterator<string> outr{rezult, "\n"};

    merge(begf, end, begs, end, outr);    // using iterators

    ofs.seekp(ios_base::beg);       // does not affect
    ofs.clear();                    // does not affect

    while(begf!=end){
        cout<<*begf;                // work only once
        begf++;
    }

    istream_iterator<string> begff{ofs};        // new iterator
    while(begff!=end){
        cout<<*begff;               // dont work even once
        begff++;
    }
}

Upd:
If i use

ofs.clear();
ofs.seekp(ios_base::beg); 

and then continue to use same istream_iterator first and second dereference give same value, so need to use

begf++;

to skip duplicates.


Solution

  • Call clear before seekp, as there are fail and/or eof bits which are not handled by seekp

    ofs.clear();
    ofs.seekp(ios_base::beg);