gpt4 book ai didi

c++ - 如何将字符串流中的数据写入文件(CPP)

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:57:50 26 4
gpt4 key购买 nike

我有一个函数,它是从库中回调的,如下所示:

void onCallBack(int date, const std::stringstream &data); 

我想写入从 data 接收到的数据物理文件的变量,所以我这样做:

void onCallBack(int date, const std::stringstream &data)
{
ofstream filePtr;
filePtr.open("data.file", ios::app);

string dataToWrite = data.str();
filePtr << dataToWrite.c_str();

filePtr.close();
}

回电onCallBack每当数据更新时都会调用函数,我想将更新后的数据写入文件。

问题是数据是std::stringstream类型,它的行为就像一个文件/缓冲区,并且我只想从这个缓冲区读取更新数据部分,例如:

在第一个回调data包含字符串
this is first line

在第二次回调中它包含:
this is first line<br/>
this is second line

在我写的回调函数的第一次调用中 this is first line字符串到文件,在第二次回调中我只想写 this is second line再次归档不是第一行。

我怎样才能只提取 std::stringstream 的更新部分? .

const std::stringstream &data变量是常量,不能修改或者我们不能使用 tellgsync .

更新/编辑:
1. 对不起 c 标签。
2. 使用read我们需要提供要读取的 block 大小,但我不知道 block 大小。
3. 你能提供一个使用 ios_base::xalloc、ios:base::iword 和 ios_base::pword 执行此操作的示例吗?
4. read 不是 const 但 tellg 是。
5. 是的,没人打电话data.str("") ,它是来自 lib 的纯虚函数,在我的代码中我没有这样做。

最佳答案

解决方案是记住您之前阅读了多少内容,然后根据需要只取字符串的一部分。你如何做到这一点取决于你。您可以修改回调以传递某种状态:

void onCallBack(int date, const std::stringstream &data, std::string::size_type& state); 

如果它是接口(interface)的一部分(考虑到您发布的内容,这不太可能,但这通常是执行回调的好方法)您可以将该状态存储为私有(private)成员变量。

如果您不关心可重入性并且流从不收缩,您可以在本示例中使用 static 变量作为快速破解,这是最容易在这里展示的工作方式,但是自找麻烦:

// What happens if you change the stringstream? 
// This is why you need to re-think the callback interface
static std::string::size_type state = 0;
string dataToWrite = data.str().substr(state);
state += dataToWrite.size();

关于c++ - 如何将字符串流中的数据写入文件(CPP),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7147362/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com