C++ 文件 I/O——不能同时读/写?

Yib*_*ang 5 c++ file-io

我正在编写一些简单的代码,该代码应该读取所​​有其他字符,并用随机文本文件中的“?”覆盖它们的相邻字符。例如。test.txt 包含“Hello World”;运行程序后,它会是“H?l?o?W?r?d”

下面的代码允许我从控制台窗口中的文本文件中读取所有其他字符,但是在程序结束后并且当我打开 test.txt 时,没有任何更改。需要帮助找出原因...

#include<iostream>
#include<fstream>
using namespace std;

int main()
{

    fstream data("test.txt", ios::in | ios::out); //here the test.txt can be any random text file
    while (!data.eof())
    {
        if (!data.eof())
        {
            char ch;
            data.get(ch);
            cout << "ch is now " << ch << endl;

        }


        if (!data.eof())
            data.put('?');

    }
    data.close();
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

alv*_*its 4

您忘记考虑您有 2 个流,istream并且ostream.

您需要同步这两个流的位置才能实现您想要的。我稍微修改了你的代码以展示我的意思。

#include<iostream>
#include<fstream>
using namespace std;

int main()
{
    char ch;
    fstream data("test.txt", ios::in | ios::out); //here the test.txt can be any random text file
    while (data.get(ch))
    {                
      cout << "ch is now " << ch << endl;
      data.seekg(data.tellp());   //set ostream to point to the new location that istream set
      data.put('?');
      data.seekp(data.tellg());   //set istream to point to the new location that ostream set
    }
    data.close();  // not required, as it's part of `fstream::~fstream()`
    return 0;  // not required, as 0 is returned by default
}
Run Code Online (Sandbox Code Playgroud)