Namespaces
Variants

std::basic_istream<CharT,Traits>:: sync

From cppreference.net
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 sync() 返回 traits :: eof ( ) 如果 rdbuf ( ) - > pubsync ( ) 返回 - 1 此情况下返回 - 1

参见

[virtual]
同步缓冲区与关联的字符序列
( std::basic_streambuf<CharT,Traits> 的虚保护成员函数)
与底层存储设备同步
( std::basic_ostream<CharT,Traits> 的公开成员函数)