使用fstream在读取后写入

writing after reading using fstream

本文关键字:读取 fstream 使用      更新时间:2023-10-16

我的印象是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建议。还添加了一行打印是否设置了failbit或badbit,并更新了程序输出。最终的文件内容保持不变,但是问题仍然存在。

(更详细的答案来自我在评论中发布的问题)

你需要调用flush()对输出流对象(从ostream派生),以便数据实际写入输出流。关于flush()的更多信息可在此c++参考页面获得。

此操作适用于GCC 4.9.0和VS2013。

指出:

  • seekg用于移动读指针
  • seekp用于移动写指针
在示例代码中,需要查找fs.seekp(0, std::ios::beg);行中的

。没有问题,因为读指针没有移动(在此之前没有读)。

代码:

#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;
}
string data="";
string Newdata="New Data";
std::fstream output_file(fileName,  ios::in| ios::out);
output_file >> data; //read Data
 output_file.seekg( 0, ios::beg );//set point to zero
 output_file<<Newdata<<"n"; //write new Data
 output_file.close();

一旦你使用fstream读取文件,告诉<读取指针>并告诉<写指针>指向-1。为了能够再次使用fstream写入,只需调用fstream.clear(),它会将读写指针重置到读取前的位置。

上面发布的解决方案都不起作用,但fstream.clear()有效。