名前空間
変種
操作

std::basic_ofstream<CharT,Traits>::swap

From cppreference.com
< cpp‎ | io‎ | basic ofstream
 
 
 
 
void swap( basic_ofstream& other );
(C++11以降)

ストリームの状態をotherの状態と交換します。

これは、basic_ostream<CharT, Traits>::swap(other) および rdbuf()->swap(other.rdbuf()) を呼び出すことによって行われます。

目次

[編集] パラメータ

その他 - 状態を交換するストリーム

[編集] 戻り値

(なし)

[編集] 例外

実装定義の例外をスローする場合があります。

[編集]

#include <fstream>
#include <iomanip>
#include <iostream>
#include <string>
 
bool create_stream(std::fstream& fs, const std::string& path)
{
    try
    {
        std::fstream ts{path, ts.trunc | ts.in | ts.out};
        if (ts.is_open())
        {
            ts.swap(fs); // stream objects are not copyable
            return true;
        }
    }
    catch (...)
    {
        std::cout << "Exception!\n";
    }
    return false;
}
 
void use_stream(std::fstream& fs)
{
    fs.seekg(0);
    std::string data;
    fs >> data;
    std::cout << "data: " << std::quoted(data) << '\n';
}
 
int main()
{
    std::fstream fs;
    std::string path = "/tmp/test_file.txt";
    if (create_stream(fs, path))
    {
        fs.write(path.c_str(), path.length());
        use_stream(fs);
    }
}

実行結果の例

data: "/tmp/test_file.txt"

[編集] 関連項目

(C++11)
ファイルストリームを移動する
(public member function) [編集]
(C++11)
2つのbasic_filebufオブジェクトを交換します
(std::basic_filebuf<CharT,Traits>のメンバ関数(public)) [編集]
English 日本語 中文(简体) 中文(繁體)