std::basic_istream<CharT,Traits>::sync
来自 cppreference.cn
< 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> 的公有成员函数) |