可以插入 fstream,但不能插入 iostream

Can insert in an fstream, but not in an iostream

正在尝试在文件中间插入一个字符串,从结尾开始。

以下代码适用于 fstream,但不适用于 iostream(在这种情况下,输出字符串等于输入字符串):

    // 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;
        }
    }

输出:
情况 1:开始 = abcdefghijklmnopqrstxyz;结果 = abcdefghijklmnopqrstuvwxyz
情况 2:开始 = abcdefghijklmnopqrstxyz;结果 = abcdefghijklmnopqrstxyz

我是不是做错了什么,或者我根本无法在 iostream 中插入?

通用 iostream 不可搜索 - 想想键盘或打印机。

您没有检查 seekp 操作的结果。它可能会失败并将流设置为错误状态。任何进一步的输出尝试都将无济于事。