std::basic_istream<CharT,Traits>::sync
來自 cppreference.com
< cpp | io | basic istream
int sync(); |
||
將輸入緩衝區與關聯的資料來源同步。
行為類似於 UnformattedInputFunction,但 gcount() 不受影響。在構造並檢查哨兵物件後,
如果 rdbuf() 為空指標,則返回 -1。
否則,呼叫 rdbuf()->pubsync()。如果該函式返回 -1,則呼叫 setstate(badbit) 並返回 -1。否則,返回 0。
目錄 |
[編輯] 引數
(無)
[編輯] 返回值
成功時返回 0,失敗或流不支援此操作(未緩衝)時返回 -1。
[編輯] 注意
與 readsome() 一樣,此函式是否對庫提供的流執行任何操作是實現定義的。其意圖通常是讓下一次讀取操作獲取自流緩衝區上次填充其獲取區域後可能對關聯輸入序列所做的任何更改。為實現此目的,sync()
可能會清空獲取區域,或者重新填充它,或者不執行任何操作。一個值得注意的例外是 Visual Studio,當使用標準輸入流呼叫此操作時,它會丟棄未處理的輸入。
[編輯] 示例
演示了輸入流 sync()
與檔案輸入的使用。請注意,這裡的輸出是實現定義的,因為對於讀取,對 std::basic_filebuf::sync 的呼叫是實現定義的。
執行此程式碼
#include <fstream> #include <iostream> void file_abc() { std::ofstream f("test.txt"); f << "abc\n"; } void file_123() { std::ofstream f("test.txt"); f << "123\n"; } int main() { file_abc(); // file now contains "abc" std::ifstream f("test.txt"); std::cout << "Reading from the file\n"; char c; f >> c; std::cout << c; file_123(); // file now contains "123" f >> c; std::cout << c; f >> c; std::cout << c << '\n'; f.close(); file_abc(); // file now contains "abc" f.open("test.txt"); std::cout << "Reading from the file, with sync()\n"; f >> c; std::cout << c; file_123(); // file now contains "123" f.sync(); f >> c; std::cout << c; f >> c; std::cout << c << '\n'; }
可能的輸出
Reading from the file abc Reading from the file, with sync() a23
[編輯] 缺陷報告
下列更改行為的缺陷報告追溯地應用於以前出版的 C++ 標準。
缺陷報告 | 應用於 | 釋出時的行為 | 正確的行為 |
---|---|---|---|
LWG 62 | C++98 | 如果 rdbuf()->pubsync() 返回 -1,則 sync() 返回 traits::eof() |
在這種情況下返回 -1 |
[編輯] 參見
[虛擬函式] |
將緩衝區與關聯的字元序列同步 ( std::basic_streambuf<CharT,Traits> 的虛保護成員函式) |
與底層儲存裝置同步 ( std::basic_ostream<CharT,Traits> 的公有成員函式) |