std::basic_fstream<CharT,Traits>::swap
來自 cppreference.com
< cpp | io | basic_fstream
void swap( basic_fstream& other ); |
(C++11 起) | |
交換流的狀態與 other 的狀態。
這是透過呼叫 basic_iostream<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> 的公共成員函式) |