Namespaces
Variants

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

From cppreference.net

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)
移动文件流
(公开成员函数)
(C++11)
交换两个 basic_filebuf 对象
(std::basic_filebuf<CharT,Traits> 的公开成员函数)