【问题标题】:C++ File I/O--can't read/write simultaneously?C++ 文件 I/O——不能同时读/写?
【发布时间】:2014-10-07 02:06:15
【问题描述】:

我正在编写一些简单的代码,该代码应该读取所​​有其他字符,并在随机文本文件中用 '?' 覆盖它们的相邻字符。 例如。 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;
}

【问题讨论】:

  • 保证您的第一个if 被占用;毕竟您的while 条件完全相同(!data.eof())。
  • 也许您在多个目录中有多个test.txt
  • 这里的问题是您没有考虑到您有 2 个流(istreamostream)。当指向istream 的指针移动时,指向ostream 的指针仍在旧位置。
  • data.eof() 在这段代码中被使用了 3 次太多

标签: c++ file-io


【解决方案1】:

您忘了考虑您有 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
}

【讨论】:

  • @alvtis:谢谢你的建议——我确实忘记了这两个指针。我运行了您的代码,它确实将“Hello World”重写为“H?l?o?W?r?d”。但是,我遇到了一个无限循环,其中 istream 指针卡在字符“d”上......我认为它与结尾的空终止符有关
  • @YiboYang,我已经解决了这个问题。通过将!data.eof() 替换为data.get(ch)。但是一个小问题仍然存在,因为“Hello World”被“H?l?o?W?r?d?”取代。看最后一个“?”它替换了 NUL 字符。
【解决方案2】:

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

【讨论】:

  • 确实如此,但不是他遇到的问题。
  • 在不查找的情况下像这样读取然后写入文件是未定义的行为,see here
猜你喜欢
  • 2016-01-30
  • 1970-01-01
  • 2023-03-08
  • 1970-01-01
  • 1970-01-01
  • 2013-11-09
  • 2017-04-25
  • 2015-08-06
  • 2013-09-09
相关资源
最近更新 更多