std::basic_istream<CharT,Traits>::sync
来自 cppreference.cn
< cpp | io | basic istream
int sync(); |
||
使输入缓冲区与关联的数据源同步。
行为如同 UnformattedInputFunction,除了 gcount() 不受影响。在构造和检查 sentry 对象之后,
如果 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++ 标准。
DR | 应用于 | 已发布行为 | 正确行为 |
---|---|---|---|
LWG 62 | C++98 | 如果 rdbuf()->pubsync() 返回 -1,则 sync() 返回 traits::eof() |
在这种情况下返回 -1 |
[编辑] 参见
[虚函数] |
使缓冲区与关联的字符序列同步 ( std::basic_streambuf<CharT,Traits> 的虚保护成员函数) |
与底层存储设备同步 ( std::basic_ostream<CharT,Traits> 的公共成员函数) |