我有一个函数,它是一个回调从它看起来像一个图书馆如下:如何从字符串流数据写入一个文件(CPP)
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 second line
文件不再拳头线。
我该如何提取std::stringstream
的更新部分。
const std::stringstream &data
变量是不变的,不能修改或我们不能使用tellg
或sync
。
更新/编辑:
1.抱歉c标签。
2.对于使用read
,我们需要提供块大小来读取,我不知道块的大小。
3.你可以提供一个使用ios_base :: xalloc,ios:base :: iword和ios_base :: pword来做这个的例子。
4.阅读不是一个常量,但tellg是。
5.是的没有人打电话data.str("")
,它是从lib的纯虚函数,在我的代码我没有这样做。
删除了“C”的标签,因为这显然不是C. – Flexo
为什么不使用'read',而不是'str',这,大概是从缓存中删除读取字符。 –
修正了标题中的语法错误。 – Rhexis