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

异常安全

-

另见