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

时间:2014-10-07 02:06:15

标签: 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;
}

2 个答案:

答案 0 :(得分:2)

您忘了考虑有2个流,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
}

答案 1 :(得分:0)

您滥用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;
}