Pietro
Pietro

Reputation: 13172

Can insert in an fstream, but not in an iostream

Trying to insert a string in the middle of a file, starting from its end.

The following code works with an fstream, but not with an iostream (in this case the output string is equal to the input one):

    // File contents: "abcdefghijklmnopqrstxyz"; "uvw" missing

    // 1 - OK
    //fstream  iofs(fPath, ios_base::in | ios_base::out);

    // 2 - Same output
    filebuf   fileBuffer;
    iostream  iofs(&fileBuffer);    // generic output stream
    fileBuffer.open(fPath.c_str(), ios_base::in | ios_base::out | ofstream::app);
    iofs.rdbuf(&fileBuffer);

    iofs.seekg(0, ios_base::end);
    iofs.seekp(0, ios_base::end);

    for(int i = 1; i < 20; ++i)
    {
        iofs.seekg(-i, std::ios_base::end);

        char c = char(iofs.peek());

        if(c == 't') {
            iofs.seekp(-i + 1, std::ios_base::end);
            iofs << "uvw";      // add missing token
            iofs << "xyz";      // append pre-existing token
            break;
        }
    }

Output:
Case 1: Begin = abcdefghijklmnopqrstxyz; Result = abcdefghijklmnopqrstuvwxyz
Case 2: Begin = abcdefghijklmnopqrstxyz; Result = abcdefghijklmnopqrstxyz

Am I doing something wrong, or I simply cannot do an insert in a iostream?

Upvotes: 0

Views: 93

Answers (1)

Bo Persson
Bo Persson

Reputation: 92301

A generic iostream is not seekable - think keyboard or printer.

You don't check the result of the seekp operation. It probably fails and sets the stream into an error state. Any further output attempts will then do nothing.

Upvotes: 3

Related Questions