C++ 文件 I/O - 无法同时读取/写入?

C++ File I/O--can't read/write simultaneously?

本文关键字:读取 写入 文件 C++      更新时间:2023-10-16

我正在写一些简单的代码,应该每隔一个字符读取一次,并用"?"覆盖它们相邻的字符s在一个随机文本文件中。例如。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;
}

您忘记考虑您有两个流,istreamostream

您需要同步这两个流的位置以实现您想要的内容。我修改了你的代码,以表明我的意思。

#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
}

您滥用了eof()。改为这样做:

#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
    char ch;
    while (data.get(ch))
    {
        cout << "ch is now " << ch << endl;
        data.put('?');
    }
    data.close();
    return 0;
}