c++ - 如何使用单个 fstream 创建、读取和写入文件

标签 c++ fstream

我想通过 fstream 访问一个文件,并满足以下要求:

  • 如果文件不存在,则创建它
  • 可以读取文件(从pos 0开始)
  • 文件可以被(覆盖)写入(从pos 0开始)
  • 无需关闭并重新打开文件

ios_base::in 似乎禁用了文件创建
ios_base::out 似乎禁用文件读取

这可能吗?怎么办?

#include <iostream>
#include <sstream>
#include <fstream>
#include <cassert>

using namespace std;

int main()
{
   auto mode = ios_base::in|ios_base::out;
   std::string filePath = "./test.txt";
   std::string content1 = "Any content 1";
   std::string content2 = "Any content 2";

   {
        std::remove(filePath.c_str());
   }

   {// Test creation
       // make sure test.txt is missing / does not exists
       fstream file(filePath, mode);
       assert(file.is_open() && file.good());
       file << content1;
   }

   { // Test reading & writing
       fstream file(filePath, mode);

       // read
       file.seekg(0);
       std::stringstream buffer1;
       buffer1 << file.rdbuf();
       cout << buffer1.str() << endl;
       assert(buffer1.str()==content1);

       // write
       file.seekp(0);
       file << content2;
       assert(file.is_open() && file.good());

       // read
       file.seekg(0);
       std::stringstream buffer2;
       buffer2 << file.rdbuf();
       cout << buffer2.str() << endl;
       assert(buffer2.str()==content2);
   }

    return 0;
}

Run it

最佳答案

只有 fstream 我会拒绝。

你可能想要一些与 trunc 模式类似的东西,但如果文件存在,你将丢失所有内容(这可能是个问题,如果不使用 trunc + out)

另一种方法是检查文件是否存在,如果不存在则创建它(无论哪种方式)。然后你用 In 和 Out 打开并做你的事情。

从 cpp 的角度来看,能够读取您刚创建的空文件的内容是没有意义的

关于c++ - 如何使用单个 fstream 创建、读取和写入文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58956938/

相关文章:

c++ - 显式模板实例化是否在 cpp 或头文件中?

c++ - 将迭代器返回到 STL 容器中的元素

c++ - Gstreamer 录制带音频的视频

C++ std::getline 结果字符串不允许我将另一个字符串连接到它

c++ - 如何从 C++ Vector 中删除尾随 0

c++ - 如何检查 C++ 类中的内存泄漏?

c++ - 读入单词搜索游戏 C++ 的文件

c++ - 将固定长度的记录写入文件 C++

c++ - 使用 C++ 修复 .txt 文件中的列宽

c++ - 如何返回 fstream (C++0x)