简体   繁体   English

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

[英]How to use a single fstream for creation, reading and writing a file

I would like to access a file through fstream with the following requirements:我想通过fstream访问具有以下要求的文件:

  • If the files does not exists, it create it如果文件不存在,则创建它
  • The file can be read (from pos 0)可以读取文件(从 pos 0)
  • The file can be (over)written (from pos 0)该文件可以(覆盖)写入(从 pos 0)
  • Without closing and re-opening the file无需关闭并重新打开文件

ios_base::in seems to disable file creation ios_base::in似乎禁用文件创建
ios_base::out seems to disable file reading ios_base::out似乎禁用文件读取

Is this possible?这可能吗? How?如何?

#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运行

Only with fstream I'd say no.只有使用 fstream 我才会说不。

You might want to have something similar with the trunc mode but you'll lose everything if the file exists (which might be a problem, if not go for trunc + out)您可能希望与 trunc 模式类似,但如果文件存在,您将丢失所有内容(如果不是 go 用于 trunc + out,这可能是一个问题)

The other way is to check if the file exists, if not you create it (whichever way).另一种方法是检查文件是否存在,如果不存在,则创建它(无论哪种方式)。 Then you open with In and Out and do your stuff.然后你用 In 和 Out 打开并做你的事情。

It kind of doesn't make sense to be able to read inside an empty file you just created from the cpp point of view从 cpp 的角度来看,能够读取刚刚创建的空文件是没有意义的

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

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