使用fstream读取后写

问题描述 投票:1回答:4

我给人的印象是c ++中的fstream对象可用于使用同一流读取和写入。我已经成功地能够首先写入流,然后从中读取。但是,如果我尝试再次写入该文件,则该文件不会受到影响。

这里是一个使用MinGw在Windows上成功编译的代码示例:

int main()
{
    std::string path="file.txt";

    std::fstream fs(path.c_str());
    int buffSize=100;
    int bytesRead=0;
    char* buffer=new char[buffSize];

    fs.write("hello", 5);
    fs.seekp(0, std::ios::beg);
    fs.read(buffer, buffSize);
    bytesRead=fs.gcount();
    for(int i=0;i<bytesRead;i++) {std::cout << buffer[i];}
    std::cout << "\n";
    fs.clear();
    fs.seekp(1, std::ios::beg);
    fs.write("E", 1);
    std::cout << "fail: " << fs.fail() << "\n";

    delete[] buffer;
}

“ file.txt”的初始内容仅为:

AAAAAAA

程序输出:

helloAA
fail: 0

运行程序后在文本编辑器中查看文件,显示最终内容是:

helloAA

“ E”的最终文字未生效,为什么会这样,我该如何解决?

编辑:

我尝试使用fs.clear(),然后按照用户0x499602D2的建议再次写入。还增加了一行,打印出是否设置了故障位或故障位,并更新了程序输出。最终文件内容保持不变,但是问题仍然存在。

c++ io fstream
4个回答
1
投票

((我在问题评论中发布的内容提供了更详细的答案)

您需要在输出流对象(从ostream派生)上调用flush(),以便将数据实际写入输出流。有关flush()的更多信息,请参见on this c++ reference page


0
投票

此工作在GCC 4.9.0和VS2013中。

注意:

  • seekg用于移动读取的指针
  • seekp用于移动写指针

在[C0行中的示例代码中,需要查找。没问题,因为读取指针没有移动(直到那里都没有读取)。

代码:

fs.seekp(0, std::ios::beg);

0
投票
#include <algorithm>
#include <iostream>
#include <fstream>

using namespace std;

int main(int argc, char* argv[]) {
  std::string path = "H:\\save.txt";

  int buffSize = 100;
  int bytesRead = 0;
  char* buffer = new char[buffSize];

  std::fstream fs(path.c_str());
  fs.write("hello", 5);
  fs.flush();                        // flushing to disk file
  fs.seekg(0, std::ios_base::beg);   // moving the read pointer
  fs.read(buffer, buffSize);
  bytesRead = fs.gcount();
  for (int i = 0; i < bytesRead; i++) {
    std::cout << buffer[i];
  }
  std::cout << "\n";
  fs.clear();
  fs.seekp(1, std::ios::beg);
  fs.write("E", 1);
  fs.flush();                      // flushing to disk file
  std::cout << "fail: " << fs.fail() << "\n";

  delete[] buffer;

  return 0;
}

0
投票

一旦使用fstream读取文件,tellg 和tellp 指向-1。为了能够再次使用fstream进行写入,只需调用fstream.clear(),它将把读写指针重置为读取之前的位置。

以上解决方案均未发布,但fstream.clear()可行。

© www.soinside.com 2019 - 2024. All rights reserved.