public member function
<fstream>

std::ofstream::ofstream

預設 (1)
ofstream();
initialization (2)
explicit ofstream (const char* filename, ios_base::openmode mode = ios_base::out);
預設 (1)
ofstream();
initialization (2)
explicit ofstream (const char* filename, ios_base::openmode mode = ios_base::out);explicit ofstream (const string& filename, ios_base::openmode mode = ios_base::out);
copy (3)
ofstream (const ofstream&) = delete;
move (4)
ofstream (ofstream&& x);
構造物件
構造一個 ofstream 物件

(1) 預設建構函式
構造一個未與任何檔案關聯的 ofstream 物件。
在內部,其 ostream 基類建構函式會接收一個指向新構造的 filebuf 物件(內部檔案流緩衝區)的指標。
(2) 初始化建構函式
構造一個 ofstream 物件,該物件最初與由第一個引數(filename)標識的檔案關聯,並使用 mode 指定的模式開啟。
在內部,其 ostream 基類建構函式會接收一個指向新構造的 filebuf 物件(內部檔案流緩衝區)的指標。然後,使用 filenamemode 作為引數呼叫 filebuf::open
如果檔案無法開啟,則設定流的failbit標誌。
(3) 複製建構函式 (已刪除)
已刪除 (無複製建構函式)。
(4) 移動建構函式
獲取 x 的內容。
首先,該函式將 x 的基類 ostream 類和 x 的內部 filebuf 物件移動構造,然後透過呼叫成員函式 set_rdbuf 將它們關聯起來。
x 處於未指定但有效的狀態。
內部 filebuf 物件具有至少與 ofstream 物件相同的生命週期。

引數

filename
代表要開啟的檔名的字串。
有關其格式和有效性的具體說明取決於庫實現和執行環境。
mode
描述檔案請求的輸入/輸出模式的標誌。
這是一個位掩碼成員型別 openmode 的物件,由以下成員常量的組合構成:
成員常量代表access
in輸入用於讀取的檔案:內部流緩衝區 支援輸入操作。
下可用的型別 *輸出用於寫入的檔案:內部流緩衝區 支援輸出操作。
binarybinary操作以二進位制模式執行,而非文字模式。
ate在末尾輸出位置從檔案末尾開始。
appappend (追加)所有輸出操作都在檔案末尾進行,追加到其現有內容。
trunctruncate (截斷)檔案開啟前存在的任何內容都將被丟棄。
這些標誌可以透過按位或運算子(|)組合。
* 對於 ofstream 物件,out 始終設定為 true(即使在引數 mode 中未顯式設定)。
請注意,儘管 ofstream 是一個輸出流,但其內部 filebuf 物件可能被設定為也支援輸入操作。

如果模式同時設定了 truncapp,則開啟操作失敗。如果同時設定了 appin,也會失敗。
如果模式同時設定了 truncapp,則開啟操作失敗。
x
一個 ofstream 物件,其值被移動。

示例

1
2
3
4
5
6
7
8
9
10
11
12
13
// ofstream constructor.
#include <fstream>      // std::ofstream

int main () {

  std::ofstream ofs ("test.txt", std::ofstream::out);

  ofs << "lorem ipsum";

  ofs.close();

  return 0;
}

資料競爭

移動建構函式 (4) 會修改 x

異常安全

-

另見