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

C++ 如何将数据从stringstream写入文件(CPP),c++,C++,我有一个函数,它是一个库的回调函数,如下所示: void onCallBack(int date, const std::stringstream &data); 我想将从数据变量接收的数据写入物理文件,因此我正在执行以下操作: void onCallBack(int date, const std::stringstream &data) { ofstream filePtr; filePtr.open("data.file", ios::app);

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

void onCallBack(int date, const std::stringstream &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();
}
void onCallBack(int-date,const-std::stringstream&data)
{
流文件处理器;
filePtr.open(“data.file”,ios::app);
字符串dataToWrite=data.str();

filePtr解决方案是记住您以前读过多少,然后根据需要只获取字符串的一部分。如何操作取决于您。您可以修改回拨以传递某种状态:

void onCallBack(int date, const std::stringstream &data, std::string::size_type& state); 
如果它是接口的一部分(考虑到您发布的内容,这不太可能,但这通常是执行回调的好方法),那么可以将该状态存储为私有成员变量

如果您不关心可重入性,并且流从不收缩,那么您可以在本例中使用
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();

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

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

filePtr您可以在写入文件之前清除文件内容,方法是将
ios::app
替换为
ios::trunc


显然,每次写入整个流并不是最佳选择,但是如果您无法更改原型或刷新流,并且您不知道新数据的大小,那么我认为这是唯一可以考虑的方法。

删除了“C”标记,因为这显然不是C。为什么不使用
读取
而不是
str
,这是可以假定的ly从缓冲区中删除读取的字符。修复了标题中的语法错误。您可能更希望重置stringstreams内容,而不是检查任何可能的未写入数据。您的代码是否确保没有人重置stringstream数据,
data.str(“”)您是否考虑从字符串流缓冲区继承,挂钩到<代码> XSPRNN<代码>、<代码>溢出>代码>和/或可能需要什么?(我没有详细检查,因此没有答案)。欢迎使用stackoverflow。我已经编辑了您的答案,为您包含的代码添加了标记。是的,它可以工作。请参阅:感谢您的回复,我无法修改回拨原型,并且您给定的解决方案无法工作:(,我尝试添加
size\u type
substr
。经过5到10次迭代后,
dataToWrite
变为空白。@psp1:这意味着要么没有向流添加任何新内容,要么流的大小缩小(已重置?)。那么什么是最好的解决方案呢?我在过去的两天里一直在忙这个。不,这是不可能的,因为最后我们没有得到完整的文件,文件将作为堆栈FILO(管道)提供给它,它只会重复部分数据。