繁体   English   中英

使用 fstream 读取后写入

[英]writing after reading using fstream

我的印象是 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”没有生效,这是为什么,我该如何解决?

编辑:

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

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

您需要在输出流对象(派生自 ostream flush()上调用flush()以便将数据实际写入输出流。 此 c++ 参考页上提供有关flush()更多信息。

这项工作在 GCC 4.9.0 和 VS2013 中进行。

笔记:

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

fs.seekp(0, std::ios::beg);行的示例代码中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 读取文件后,tellg <读取指针> 和tellp <写入指针> 指向-1。 为了能够使用 fstream 再次写入,只需调用 fstream.clear() 它将读取和写入指针重置为读取之前的位置。

上面发布的解决方案均无效,但 fstream.clear() 有效。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM