std::basic_ifstream<CharT,Traits>::basic_ifstream
来自cppreference.com
<tbody>
</tbody>
basic_ifstream(); |
(1) | |
explicit basic_ifstream( const char* filename, {{#pad:|14}} std::ios_base::openmode mode {{#pad:|14}} = std::ios_base::in ); |
(2) | |
explicit basic_ifstream( const std::filesystem::path::value_type* filename, {{#pad:|14}} std::ios_base::openmode mode {{#pad:|14}} = std::ios_base::in ); |
(3) | (C++17 起) |
explicit basic_ifstream( const std::string& filename, {{#pad:|14}} std::ios_base::openmode mode {{#pad:|14}} = std::ios_base::in ); |
(4) | (C++11 起) |
template< class FsPath > explicit basic_ifstream( const FsPath& filename, {{#pad:|14}} std::ios_base::openmode mode {{#pad:|14}} = std::ios_base::in ); |
(5) | (C++17 起) |
basic_ifstream( basic_ifstream&& other ); |
(6) | (C++11 起) |
basic_ifstream( const basic_ifstream& rhs) = delete; |
(7) | (C++11 起) |
构造新的文件流。
1) 默认构造函数:构造不关联到文件的流:默认构造 std::basic_filebuf 并构造拥有指向此默认构造的 std::basic_filebuf 成员的基类。
2,3) 首先,进行同默认构造函数的步骤,然后通过调用
rdbuf()->open(filename, mode | std::ios_base::in)关联流与文件(该调用效果上的细节见 std::basic_filebuf::open)。如果 open() 调用返回了空指针,那么就会设置 setstate(failbit)。只有在 std::filesystem::path::value_type 不是 char 时才会提供重载 (3)。(C++17 起)4,5) 同
basic_ifstream(filename.c_str(), mode)。(5) 只有在 FsPath 是 std::filesystem::path 时才会参与重载决议。(C++17 起)6) 移动构造函数:首先,从
other 移动构造基类(这不影响 rdbuf() 指针),然后移动构造 std::basic_filebuf 成员,再调用 this->set_rdbuf() 安装新的 basic_filebuf 为基类中的 rdbuf() 指针。7) 复制构造函数被弃置:此类不可复制。
参数
| filename | - | 要打开的文件名 | ||||||||||||||||
| mode | - | 指定打开模式。可使用下列常量或它们之间的逐位或:
| ||||||||||||||||
| other | - | 用作源的另一文件流 |
示例
运行此代码
#include <fstream>
#include <string>
#include <utility>
int main()
{
std::ifstream f0;
std::ifstream f1("test.bin", std::ios::binary);
std::string name = "example.txt";
std::ifstream f2(name);
std::ifstream f3(std::move(f1));
}
缺陷报告
下列更改行为的缺陷报告追溯地应用于以前出版的 C++ 标准。
| 缺陷报告 | 应用于 | 出版时的行为 | 正确行为 |
|---|---|---|---|
| LWG 3430 | C++17 | std::filesystem::path 重载导致了不想要的转换 | 使之为模板以避免 |
参阅
| 打开文件,并将它与流关联 (公开成员函数) | |
| 打开文件并配置它为关联字符序列 ( std::basic_filebuf<CharT,Traits> 的公开成员函数)
| |
替换 rdbuf 而不清除其错误状态 (受保护成员函数) | |
| 构造对象 ( std::basic_istream<CharT,Traits> 的公开成员函数)
|