公有成員函式
<fstream>

std::filebuf::open

filebuf* open (const char* filename,  ios_base::openmode mode);
filebuf* open (const char* filename,  ios_base::openmode mode);filebuf* open (const string filename, ios_base::openmode mode);
開啟檔案
開啟由引數 filename 標識的檔案,將其內容與檔案流緩衝區物件關聯,以便對其執行輸入/輸出操作。允許的操作和一些操作細節取決於引數 mode

如果該物件已與檔案關聯(即,它已開啟),則此函式失敗。

引數

filename
包含要開啟的檔案的名稱的字串。
mode
描述檔案請求的輸入/輸出模式的標誌。
這是位掩碼型別 ios_base::openmode 的物件,它由以下常量的組合構成:
代表access
ios_base::in輸入檔案以讀取模式開啟,支援輸入操作。
ios_base::out輸出檔案以寫入模式開啟,支援輸出操作。
ios_base::binarybinary操作以二進位制模式執行,而非文字模式。
ios_base::ate在末尾put 指標pptr)位於受控輸出序列的末尾。
ios_base::appappend (追加)所有輸出操作都在檔案末尾進行,追加到其現有內容。
ios_base::trunctruncate (截斷)檔案開啟前存在的任何內容都將被丟棄。
這些標誌可以透過按位或運算子(|)組合。

如果模式同時設定了 ios_base::truncios_base::app,則開啟操作失敗。如果設定了其中一個但未設定 ios_base::out,或者同時設定了 ios_base::appios_base::in,則也失敗。
如果模式同時設定了 ios_base::truncios_base::app,則開啟操作失敗。如果設定了 ios_base::trunc 但未設定 ios_base::out,也失敗。

返回值

如果成功,函式返回 this
如果失敗,檔案未開啟,並返回一個空指標

示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// filebuf::open()
#include <iostream>
#include <fstream>

int main () {
  std::ifstream is;
  std::filebuf * fb = is.rdbuf();

  fb->open ("test.txt",std::ios::out|std::ios::app);

  // >> appending operations here <<

  fb->close();

  return 0;
}

資料競爭

修改 filebuf 物件。
同時訪問同一個檔案流緩衝區物件可能導致資料爭用。

異常安全

基本保證:如果丟擲異常,*檔案流緩衝區*處於有效狀態。

另見