public member function
<fstream>

std::basic_ifstream::basic_ifstream

默认 (1)
basic_ifstream();
initialization (2)
explicit basic_ifstream (const char* filename,                         ios_base::openmode mode = ios_base::in);
默认 (1)
basic_ifstream();
initialization (2)
explicit basic_ifstream (const char* filename,                         ios_base::openmode mode = ios_base::in);explicit basic_ifstream (const string& filename,                         ios_base::openmode mode = ios_base::in);
copy (3)
basic_ifstream (const basic_ifstream&) = delete;
move (4)
basic_ifstream (basic_ifstream&& x);
构造对象
Constructs a basic_ifstream object

(1) 默认构造函数
Constructs a basic_ifstream object that is not associated with any file.
Internally, its basic_istream base constructor is passed a pointer to a newly constructed basic_filebuf object (the internal file stream buffer).
(2) initialization constructor
Constructs a basic_ifstream object, initially associated with the file identified by its first argument (filename), open with the mode specified by mode.
Internally, its basic_istream base constructor is passed a pointer to a newly constructed basic_filebuf object (the internal file stream buffer). Then, basic_filebuf::open is called with filename and mode as arguments.
如果文件无法打开,则设置流的failbit标志。
(3) 复制构造函数 (已删除)
已删除 (无复制构造函数)。
(4) move constructor
获取 x 的内容。
First, the function move-constructs both its base basic_istream class from x and a basic_filebuf object from x's internal basic_filebuf object, and then associates them by calling member set_rdbuf.
x 处于未指定但有效的状态。
The internal basic_filebuf object has at least the same duration as the basic_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 basic_ifstream objects (even if explicitly not set in argument mode).
Note that even though basic_ifstream is an input stream, its internal basic_filebuf object may be set to also support output operations.

如果模式设置了 app,则打开操作失败。如果设置了 trunc 但未设置 out,操作也会失败。
如果模式同时设置了 truncapp,则打开操作失败。如果设置了 trunc 但未设置 out,操作也会失败。
x
A basic_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

异常安全

-

另见