名稱空間
變體
操作

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

來自 cppreference.com
< cpp‎ | io‎ | basic filebuf
 
 
 
 
basic_filebuf* open( const char* s, std::ios_base::openmode mode );
(1)
basic_filebuf* open( const std::string& str, std::ios_base::openmode mode );
(2) (C++11 起)
basic_filebuf* open( const std::filesystem::path& p,
                     std::ios_base::openmode mode );
(3) (C++17 起)
basic_filebuf* open( const std::filesystem::path::value_type* s,
                     std::ios_base::openmode mode );
(4) (C++17 起)

如果關聯檔案已開啟(is_open() != false),則立即返回空指標。

否則,使用給定名稱(sp.c_str()(C++17 起)str.c_str(),取決於過載)開啟檔案。std::ios_base::openmode 值可以寫成,例如,std::ios_base::out | std::ios_base::app

過載 (4) 僅在 std::filesystem::path::value_type 不是 char 時提供。

(C++17 起)

檔案透過呼叫 std::fopen 開啟,第二個引數(檔案訪問模式)由 mode & ~std::ios_base::ate 的結果確定,如下所示,如果結果不是表中所示標誌的某種組合,則 open() 失敗

模式 & ~std::ios_base::ate  std::fopen 
訪問
模式
如果檔案已存在則執行的操作 如果檔案不存在則執行的操作
二進位制 in out trunc app noreplace
(C++23 起)
- + - - - - "r" 從頭開始讀取 開啟失敗
+ + - - - - "rb"
- + + - - - "r+" 錯誤
+ + + - - - "r+b"
- - + - - - "w" 銷燬內容 建立新檔案
- - + + - -
+ - + - - - "wb"
+ - + + - -
- + + + - - "w+"
+ + + + - - "w+b"
- - + - - + "wx" 開啟失敗 建立新檔案
- - + + - +
+ - + - - + "wbx"
+ - + + - +
- + + + - + "w+x"
+ + + + - + "w+bx"
- - + - + - "a" 寫入到末尾 建立新檔案
- - - - + -
+ - + - + - "ab"
+ - - - + -
- + + - + - "a+"
- + - - + -
+ + + - + - "a+b"
+ + - - + -

如果開啟操作成功且 (openmode & std::ios_base::ate) != 0 (設定了 ate 位),則將檔案位置重新定位到檔案末尾,就像透過呼叫 std::fseek(file, 0, SEEK_END) 一樣,其中 file 是呼叫 std::fopen 返回的指標。如果重新定位失敗,則呼叫 close() 並返回空指標以指示失敗。

目錄

[編輯] 引數

s, str, p - 要開啟的檔名;s 必須指向一個以 null 結尾的字串
openmode - 檔案開啟模式,std::ios_base::openmode 模式的二進位制或(OR)

[編輯] 返回值

成功時返回 this,失敗時返回空指標。

[編輯] 注意

open() 通常透過 std::basic_fstream 的建構函式或 open() 成員函式呼叫。

[編輯] 示例

#include <fstream>
#include <iostream>
 
int main()
{
    std::string filename = "Test.b";
    std::filebuf fb;
 
    // prepare a file to read
    double d = 3.14;
    if (!fb.open(filename, std::ios::binary | std::ios::out))
    {
        std::cout << "Open file " << filename << " for write failed\n";
        return 1;
    } 
    fb.sputn(reinterpret_cast<char*>(&d), sizeof d);
    fb.close();
 
    // open file for reading
    double d2 = 0.0;
    if (!fb.open(filename, std::ios::binary | std::ios::in))
    {
        std::cout << "Open file " << filename << " for read failed\n";
        return 1;
    }
 
    auto got = fb.sgetn(reinterpret_cast<char*>(&d2), sizeof d2);
    if (sizeof(d2) != got)
        std::cout << "Read of " << filename << " failed\n";
    else
        std::cout << "Read back from file: " << d2 << '\n';
}

輸出

Read back from file: 3.14

[編輯] 缺陷報告

下列更改行為的缺陷報告追溯地應用於以前出版的 C++ 標準。

缺陷報告 應用於 釋出時的行為 正確的行為
LWG 596 C++98 open() 無法以追加模式開啟檔案 可以以追加模式開啟

[編輯] 另請參閱

檢查關聯檔案是否開啟
(公共成員函式) [編輯]
重新整理輸出緩衝區並關閉關聯檔案
(公共成員函式) [編輯]