• Class / Function / Type

      std::
    • Header file

      <>
    • Other / All

    最終更新日時(UTC):
    が更新

    履歴 編集

    function
    <fstream>

    std::basic_filebuf::open

    basic_filebuf* open(const char* s, ios_base::openmode mode); // (1)
    basic_filebuf* open(const filesystem::path::value_type* s,
                        ios_base::openmode mode); // (2) C++17
    basic_filebuf* open(const string& s, ios_base::openmode mode); // (3)
    basic_filebuf* open(const filesystem::path& s, ios_base::openmode mode); // (4) C++17
    

    概要

    • (1): sで指定されたファイルを開く。sヌル終端文字列。
    • (2): std::filesystem::path::value_typeの型がcharではないときのみ定義される。効果は(1)と同じ。
    • (3): ファイルを指定する引数の型がstd::stringである点を除き、(1)と同じ。
    • (4): ファイルを指定する引数の型がstd::filesystem::pathである点を除き、(1)と同じ。

    効果

    まずmode & ~ios_base::ateの結果からファイルの開くモードが決定される。fopenのモード文字列との対応は以下の通り。

    binary in out trunc app 対応するfopenのモード文字列
    "w"
    "a"
    "a"
    "w"
    "r"
    "r+"
    "w+"
    "a+"
    "a+"
    "wb"
    "ab"
    "ab"
    "wb"
    "rb"
    "r+b"
    "w+b"
    "a+b"
    "a+b"

    そしてあたかもfopenがこのモード文字列を第二引数に指定して呼び出されたかのように振る舞う。

    ファイルを開くのに成功して、(mode & ios_base::ate) != 0の場合、ファイル終端にseekする(fseek(file, 0, SEEK_END)したかのように振る舞う)

    ファイルを開くのに失敗した場合close()を呼び出す。

    戻り値

    もしis_open()falseではない、もしくは開くのに失敗したならば、nullptrを返す。

    成功したらthisを返す

    #include <iostream>
    #include <fstream>
    
    int main()
    {
      std::fstream fs("foo");
      std::filebuf* buf = fs.rdbuf();
    
      if (buf->open("foo", std::ios_base::out)) {
          std::cout << "opened" << std::endl;
      }
    }
    

    バージョン

    言語

    • C++98
    • C++17: std::filesystem::pathへの対応

    参照