public member function
<fstream>

std::ifstream::ifstream

預設 (1)
ifstream();
initialization (2)
explicit ifstream (const char* filename, ios_base::openmode mode = ios_base::in);
預設 (1)
ifstream();
initialization (2)
explicit ifstream (const char* filename, ios_base::openmode mode = ios_base::in);explicit ifstream (const string& filename, ios_base::openmode mode = ios_base::in);
copy (3)
ifstream (const ifstream&) = delete;
move (4)
ifstream (ifstream&& x);
Construct object and optionally open file
Constructs an ifstream object

(1) 預設建構函式
Constructs an ifstream object that is not associated with any file.
Internally, its istream base constructor is passed a pointer to a newly constructed filebuf object (the internal file stream buffer).
(2) initialization constructor
Constructs an ifstream object, initially associated with the file identified by its first argument (filename), open with the mode specified by mode.
Internally, its istream base constructor is passed a pointer to a newly constructed filebuf object (the internal file stream buffer). Then, filebuf::open is called with filename and mode as arguments.
如果檔案無法開啟,則設定流的failbit標誌。
(3) 複製建構函式 (已刪除)
已刪除 (無複製建構函式)。
(4) move constructor
獲取 x 的內容。
First, the function move-constructs both its base istream class from x and a filebuf object from x's internal filebuf object, and then associates them by calling member set_rdbuf.
x 處於未指定但有效的狀態。
The internal filebuf object has at least the same duration as the ifstream object.

引數

filename
A string representing the name of the file to open.
有關其格式和有效性的具體說明取決於庫實現和執行環境。
mode
描述檔案請求的 i/o 模式的標誌。
這是一個位掩碼成員型別 openmode 的物件,由以下成員常量的組合構成:
成員常量代表access
in *輸入用於讀取的檔案:內部流緩衝區 支援輸入操作。
下可用的型別輸出用於寫入的檔案:內部流緩衝區 支援輸出操作。
binarybinary操作以二進位制模式執行,而非文字模式。
ate在末尾輸出位置從檔案末尾開始。
appappend (追加)所有輸出操作都在檔案末尾進行,追加到其現有內容。
trunctruncate (截斷)檔案開啟前存在的任何內容都將被丟棄。
這些標誌可以透過按位或運算子(|)組合。
* in is always set for ifstream objects (even if explicitly not set in argument mode).
Note that even though ifstream is an input stream, its internal filebuf object may be set to also support output operations.

如果模式設定了 app,則開啟操作失敗。如果設定了 trunc 但未設定 out,操作也會失敗。
如果模式同時設定了 truncapp,則開啟操作失敗。如果設定了 trunc 但未設定 out,操作也會失敗。
x
A ifstream object of the same type (with the same class template parameters charT and traits), whose value is moved.

示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// ifstream constructor.
#include <iostream>     // std::cout
#include <fstream>      // std::ifstream

int main () {

  std::ifstream ifs ("test.txt", std::ifstream::in);

  char c = ifs.get();

  while (ifs.good()) {
    std::cout << c;
    c = ifs.get();
  }

  ifs.close();

  return 0;
}

資料競爭

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

異常安全

-

另見