如何将数据从stringstream写入文件(CPP)

How to write data from stringstream to a file (CPP)

本文关键字:文件 CPP stringstream 数据      更新时间:2023-10-16

我有一个函数,它是一个从库回调的函数,它看起来像这样:

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
this is second line

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

如何只提取std::stringstream的更新部分?

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

更新/编辑:
1. 对不起,c标签。
2. 为了使用read,我们需要提供块大小来读取,我不知道块大小。
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); 

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

如果你不关心是否可重入,并且流永远不会收缩,你可以在这个例子中使用static变量作为快速hack来实现它,这是最容易显示在这里工作的,但是自找麻烦:

// 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();

在写入文件之前,可以将ios::app替换为ios::trunc来清空文件内容。

显然,每次都写整个流不是最佳的,但是如果你不能改变原型或刷新流,并且你不知道新数据的大小,那么我这是我能想到的唯一方法…

如果您确定 stringstream对象对于每个回调调用都是相同的,您可以这样做:

filePtr << data.rdbuf() << std::flush;