std::basic_ifstream<CharT,Traits>::swap
来自 cppreference.cn
< cpp | io | basic ifstream
void swap( basic_ifstream& other ); |
(since C++11) | |
与 other 交换流的状态。
这通过调用 basic_istream<CharT, Traits>::swap(other) 和 rdbuf()->swap(other.rdbuf()) 完成。
目录 |
[edit] 参数
other | - | 与之交换状态的流 |
[edit] 返回值
(无)
[edit] 异常
可能抛出实现定义的异常。
[edit] 示例
运行此代码
#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"
[edit] 参见
(C++11) |
operator= 移动文件流 (public member function) |
(C++11) |
交换两个 basic_filebuf 对象(public member function of std::basic_filebuf<CharT,Traits> ) |