繁体   English   中英

可以插入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:Begin = abcdefghijklmnopqrstxyz; 结果= abcdefghijklmnopqrstuvwxyz
情况2:Begin = abcdefghijklmnopqrstxyz; 结果= abcdefghijklmnopqrstxyz

我是在做错什么,还是根本无法在iostream中插入?

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

您无需检查seekp操作的结果。 它可能会失败并将流设置为错误状态。 这样,任何进一步的输出尝试都将无效。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM