名稱空間
變體
操作

std::basic_fstream<CharT,Traits>::open

來自 cppreference.com
< cpp‎ | io‎ | basic_fstream
void open( const char* filename,

           std::ios_base::openmode mode

               = std::ios_base::in | std::ios_base::out );
(1)
void open( const std::filesystem::path::value_type* filename,

           std::ios_base::openmode mode

               = std::ios_base::in | std::ios_base::out );
(2) (C++17 起)
void open( const std::string& filename,

           std::ios_base::openmode mode

               = std::ios_base::in | std::ios_base::out );
(3) (C++11 起)
void open( const std::filesystem::path& filename,

           std::ios_base::openmode mode

               = 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 - 指定流的開啟模式。它是一個 位掩碼型別,定義了以下常量:
常量 解釋
app 每次寫入前定位到流的末尾
二進位制 二進位制模式 開啟
in 為讀取而開啟
out 為寫入而開啟
trunc 開啟時丟棄流的內容
ate 開啟後立即定位到流的末尾
noreplace (C++23) 以獨佔模式開啟

[編輯] 返回值

(無)

[編輯] 示例

#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 的預設引數
缺失(它存在於 概要 中)
已新增
  1. LWG 問題 #22 的決議被覆蓋。

[編輯] 另請參見

檢查流是否關聯了檔案
(公共成員函式) [編輯]
關閉關聯的檔案
(公共成員函式) [編輯]
開啟一個檔案並將其配置為關聯字元序列
(std::basic_filebuf<CharT,Traits> 的公共成員函式) [編輯]