c++ 一行打开文件

c++ open file in one line

我有这两行代码

ifstream inputFile;
inputFile.open("data.txt");

我依稀记得有一种方法可以用一行代码来做类似的事情。 如何一行完成?

您可以使用构造函数指定文件名:

ifstream inputFile("data.txt");

查看 std::basic_ifstream (constructor) 的详细信息。

explicit basic_ifstream( const char* filename, std::ios_base::openmode mode = ios_base::in );


First, performs the same steps as the default constructor, then associates the stream with a file by calling rdbuf()->open(filename, mode | std::ios_base::in) (see std::basic_filebuf::open for the details on the effects of that call). If the open() call returns a null pointer, sets setstate(failbit)