defined in the header file <fstream>
template< class CharT, |
The class template basic_ifstream implements high-level input operations on file streams. It gives the high-level interface of std::basic_istream to a file-based stream buffer ( std::basic_filebuf ).
A typical implementation of std::basic_ifstream only holds one non-exported data member: an instance of std::basic_filebuf<CharT, Traits> .
Also defines two specializations for common character types:
type | definition |
ifstream |
basic_ifstream<char> |
wifstream |
basic_ifstream<wchar_t> |
member function
construct file stream
std::basic_ifstream<CharT,Traits>::basic_ifstream
basic_ifstream(); |
(1) | |
explicit basic_ifstream( const char* filename, |
(2) | |
explicit basic_ifstream( const std::filesystem::path::value_type* filename, |
(3) | (since C++17) |
explicit basic_ifstream( const std::string& filename, |
(4) | (since C++11) |
explicit basic_ifstream( const std::filesystem::path& filename, |
(5) | (since C++17) |
basic_ifstream( basic_ifstream&& other ); |
(6) | (since C++11) |
basic_ifstream( const basic_ifstream& rhs) = delete; |
(7) | (since C++11) |
Constructs a new file stream.
1) Default constructor: constructs a stream that is not associated with a file: constructs a std::basic_filebuf by default and constructs a base class that has members pointing to this default-constructed std::basic_filebuf.
2-3) First, perform the same steps as the default constructor, and then call rdbuf()->open(filename, mode | std::ios_base::in) (see std::basic_filebuf:: open ) to associate a stream with a file. If the open() call returns a null pointer, setstate(failbit) is set. Overload (3) is provided only if std::filesystem::path::value_type is not char. (since C++17)
4-5) 同 basic_ifstream(filename.c_str(), mode) 。
6) Move constructor: firstly, other
move to construct the base class from (this does not affect rdbuf()
the pointer), then move to construct the std::basic_filebuf member, and then call this->set_rdbuf() to install a new as the basic_filebuf
rdbuf() pointer in the base class.
7) The copy constructor is deleted: this class is not copyable.
parameter
filename | - | filename to open | ||||||||||||||
mode | - | Specifies the open mode. It is a bitmask type and defines the following constants:
|
||||||||||||||
other | - | Another file stream to use as source |
call example
#include <fstream>
#include <utility>
#include <string>
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));
return 0;
}
Destroy basic_ifstream and associated buffers, and close the file
The default destructor generated by basic_fstream will call the close method indirectly by calling the destructor of basic_filebuf. That is, the file is automatically closed on destruction.