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

出自cppreference.com
< cpp‎ | io‎ | basic ofstream
void swap( basic_ofstream& other );
(C++11 起)

交換流與 other 的狀態。

通過調用 basic_ostream<CharT, Traits>::swap(other)rdbuf()->swap(other.rdbuf()) 進行交換。

目錄

[編輯] 參數

other - 要交換狀態的流

[編輯] 返回值

(無)

[編輯] 異常

可能會拋出由實現定義的異常。

[編輯] 示例

#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); // 流对象不可复制
            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)
移動文件流
(公開成員函數) [編輯]
(C++11)
交換兩個 basic_filebuf 對象
(std::basic_filebuf<CharT,Traits> 的公開成員函數) [編輯]