打开文件

对所有 3 个文件流(ifstreamofstreamfstream)以相同的方式打开文件。

你可以直接在构造函数中打开文件:

std::ifstream ifs("foo.txt");  // ifstream: Opens file "foo.txt" for reading only.

std::ofstream ofs("foo.txt");  // ofstream: Opens file "foo.txt" for writing only.

std::fstream iofs("foo.txt");  // fstream:  Opens file "foo.txt" for reading and writing.

或者,你可以使用文件流的成员函数 open()

std::ifstream ifs;
ifs.open("bar.txt");           // ifstream: Opens file "bar.txt" for reading only.

std::ofstream ofs;
ofs.open("bar.txt");           // ofstream: Opens file "bar.txt" for writing only.

std::fstream iofs;
iofs.open("bar.txt");          // fstream:  Opens file "bar.txt" for reading and writing.

你应该始终检查文件是否已成功打开(即使在写入时)。失败可能包括:文件不存在,文件没有正确的访问权限,文件已被使用,发生磁盘错误,驱动器断开连接…检查可以按如下方式进行:

// Try to read the file 'foo.txt'.
std::ifstream ifs("fooo.txt");  // Note the typo; the file can't be opened.

// Check if the file has been opened successfully.
if (!ifs.is_open()) {
    // The file hasn't been opened; take appropriate actions here.
    throw CustomException(ifs, "File could not be opened");
}

当文件路径包含反斜杠时(例如,在 Windows 系统上),你应该正确地转义它们:

// Open the file 'c:\folder\foo.txt' on Windows.
std::ifstream ifs("c:\\folder\\foo.txt"); // using escaped backslashes

Version >= C++ 11

或使用原始文字:

// Open the file 'c:\folder\foo.txt' on Windows.
std::ifstream ifs(R"(c:\folder\foo.txt)"); // using raw literal

或者使用正斜杠代替:

// Open the file 'c:\folder\foo.txt' on Windows.
std::ifstream ifs("c:/folder/foo.txt");

Version >= C++ 11

如果要在 Windows 上的路径中打开包含非 ASCII 字符的文件,则可以使用非标准的宽字符路径参数:

// Open the file 'пример\foo.txt' on Windows.
std::ifstream ifs(LR"(пример\foo.txt)"); // using wide characters with raw literal