std::basic_ifstream<CharT,Traits>::swap
来自cppreference.com
< cpp | io | basic ifstream
void swap( basic_ifstream& other ); |
(C++11 起) | |
交换流与 other 的状态。
通过调用 basic_istream<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> 的公开成员函数) |