開啟檔案
對所有 3 個檔案流(ifstream
,ofstream
和 fstream
)以相同的方式開啟檔案。
你可以直接在建構函式中開啟檔案:
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