簡體   English   中英

如何使用單個 fstream 來創建、讀取和寫入文件

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

我想通過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;
}

運行

只有使用 fstream 我才會說不。

您可能希望與 trunc 模式類似,但如果文件存在,您將丟失所有內容(如果不是 go 用於 trunc + out,這可能是一個問題)

另一種方法是檢查文件是否存在,如果不存在,則創建它(無論哪種方式)。 然后你用 In 和 Out 打開並做你的事情。

從 cpp 的角度來看,能夠讀取剛剛創建的空文件是沒有意義的

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM