繁体   English   中英

使用fstream同时读写

[英]use fstream to read and write in the same time

我正在学习如何从文件中读取和写入。 有一个问题,当我尝试在使用fstream写入文件后读取或读取后写入(--例如文件字母中的某些内容--)
出事了。 我试着只写或读,但它奏效了。 问题是什么?

文件内容是:

abcdefgh
ijklmnopqr
stuvw
xyz

代码是:

#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
fstream ioFile;
    char ch;
    ioFile.open("search.txt", ios::in | ios::out);
    if (!ioFile)
    {
        cout << "problem opening the file";
        goto k270;
    }
    
    while (ioFile>>ch)
    {
        if (ch == 'z')
        {
            ioFile.seekp(((int)ioFile.tellg()));
             ioFile << "x";
            
            
        }
    }


    //cout<<ioFile.rdbuf();
    ioFile.close();
    k270:
    system("pause");
    return 0;
}

看看这个答案: https://stackoverflow.com/a/17567454/11829247它解释了您遇到的错误。

简短版本:输入和 output 被缓冲,只有在您强制更新两者之间的缓冲区时,交错读写才有效。

这对我有用:

#include <iostream>
#include <fstream>
#include <string>

int main()
{
    std::fstream ioFile;
    char ch;
    ioFile.open("search.txt", std::ios::in | std::ios::out);
    if (!ioFile)
    {
        std::cout << "problem opening the file";
        return 1;
    }

    while (ioFile >> ch)
    {
        if (ch == 'z')
        {
            ioFile.seekp(-1, std::ios_base::cur);
            ioFile << "x";
            ioFile.flush();
        }
    }

    ioFile.close();
    return 0;
}

区别在于我使用ioFile.seekp(-1, std::ios_base::cur); cur position 向后退一步。您也可以使用ioFile.seekp((int)ioFile.tellg() -1); - 注意-1

然后退后一步并覆盖 z 之后,使用ioFile.flush(); 强制将写入推送到文件。 这也意味着读取缓冲区已更新,否则读取操作只会退回到其缓冲区并继续读取相同的缓冲 z。

暂无
暂无

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

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