首页
学习
活动
专区
圈层
工具
发布

std::basic_istream::sync

int sync();

将输入缓冲区与相关数据源同步。

表现为UnformattedInputFunction,除了gcount()不受影响。在构造和检查哨兵对象之后,

如果rdbuf()为空指针,则返回-1...

否则,打电话rdbuf()->pubsync().如果该函数返回-1,电话setstate(badbit)和回报-1.否则,返回​0​...

参数

%280%29

返回值

​0​在成功的时候,-1如果失败或流不支持此操作,%28将被取消缓冲%29。

注记

和...一样readsome(),它是实现定义的,该函数是否对库提供的流执行任何操作。通常情况下,下一次读取操作的目的是获取在流缓冲区最后填充其GET区域后可能对相关输入序列所做的任何更改。为了达到这个目的,sync()可以清空GET区域,也可以填充GET区域,或者什么也不做。一个值得注意的例外是VisualStudio,该操作在使用标准输入流调用时丢弃未处理的输入。

演示如何将输入流同步%28%29与文件输入一起使用,并在某些平台上实现。

二次

代码语言:javascript
代码运行次数:0
复制
#include <iostream>
#include <fstream>
 
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';
}

二次

可能的产出:

二次

代码语言:javascript
代码运行次数:0
复制
Reading from the file
abc
Reading from the file, with sync()
a23

二次

另见

sync virtual

synchronizes the buffers with the associated character sequence (virtual protected member function of std::basic_streambuf)

flush

synchronizes with the underlying storage device (public member function of std::basic_ostream)

代码语言:txt
复制
 © cppreference.com

在CreativeCommonsAttribution下授权-ShareAlike未移植许可v3.0。

扫码关注腾讯云开发者

领取腾讯云代金券