std::basic_fstream<CharT,Traits>::open
來自 cppreference.com
< cpp | io | basic_fstream
void open( const char* filename, = std::ios_base::in | std::ios_base::out ); |
(1) | |
void open( const std::filesystem::path::value_type* filename, = std::ios_base::in | std::ios_base::out ); |
(2) | (C++17 起) |
void open( const std::string& filename, = std::ios_base::in | std::ios_base::out ); |
(3) | (C++11 起) |
void open( const std::filesystem::path& filename, = std::ios_base::in | std::ios_base::out ); |
(4) | (C++17 起) |
開啟檔案,並將檔案流與名為 filename 的檔案關聯起來。
成功時呼叫 clear()。失敗時呼叫 setstate(failbit)。
1,2) 實際呼叫 rdbuf()->open(filename, mode) (關於該呼叫的效果的詳細資訊,請參閱 std::basic_filebuf::open)。 過載 (2) 僅在
std::filesystem::path::value_type
不是 char 時提供。(C++17 起)3,4) 實際呼叫 (1,2),如同透過 open(filename.c_str(), mode)。
目錄 |
[編輯] 引數
filename | - | 要開啟的檔名 | ||||||||||||||||
mode | - | 指定流的開啟模式。它是一個 位掩碼型別,定義了以下常量:
|
[編輯] 返回值
(無)
[編輯] 示例
執行此程式碼
#include <fstream> #include <iostream> #include <string> int main() { std::string filename = "example.123"; std::fstream fs; fs.open(filename); if (!fs.is_open()) { fs.clear(); fs.open(filename, std::ios::out); // create file fs.close(); fs.open(filename); } std::cout << std::boolalpha; std::cout << "fs.is_open() = " << fs.is_open() << '\n'; std::cout << "fs.good() = " << fs.good() << '\n'; }
[編輯] 缺陷報告
下列更改行為的缺陷報告追溯地應用於以前出版的 C++ 標準。
缺陷報告 | 應用於 | 釋出時的行為 | 正確的行為 |
---|---|---|---|
LWG 22 | C++98 | 成功開啟後錯誤狀態如何變化不清楚 | 錯誤狀態未改變 |
LWG 409 | C++98 | 成功開啟後錯誤狀態未改變 | 已清除[1] |
LWG 460 | C++98 | 過載 (1) 中 mode 的預設引數 缺失(它存在於 概要 中) |
已新增 |
- ↑ LWG 問題 #22 的決議被覆蓋。
[編輯] 另請參見
檢查流是否關聯了檔案 (公共成員函式) | |
關閉關聯的檔案 (公共成員函式) | |
開啟一個檔案並將其配置為關聯字元序列 ( std::basic_filebuf<CharT,Traits> 的公共成員函式) |