如何跟踪std::stringstream中的当前位置
how to keep track of the current position in std::stringstream
我正在编写一个自定义日志记录器,我在std::stringstream
中缓冲我的日志消息,并在std::stringstream
足够大时将其刷新到文件(std::ofstream
)(以节省一些IO延迟)。由于std::stringstream
没有.size()
方法,我使用seekg
和tellg
:
template <typename T>
MyClass & operator<< (const T& val)
{
boost::unique_lock<boost::mutex> lock(mutexOutput);
output << val; //std::stringstream output;
output.seekg(0, std::ios::end);
if(output.tellg() > 1048576/*1MB*/){
flushLog();
}
return *this;
}
问题:在我看来,每当我调用这个方法时,它都会使用seekg
开始从开始一直到结束计数字节,并使用tellg
获得大小。我提出这种设计首先是为了节省一些IO时间,但是:这种连续计数是否会带来更大的成本(如果对该方法的调用数量很高,并且日志消息很少,就像大多数情况一样)?
是否有更好的方法来做到这一点?
和一个侧面的问题:1MB
是一个很好的数字缓冲大小在一个正常的计算机现在?
谢谢
您可以使用ostringstream::tellp()
来获取字符串的长度。下面的例子摘自http://en.cppreference.com/w/cpp/io/basic_ostream/tellp.
#include <iostream>
#include <sstream>
int main()
{
std::ostringstream s;
std::cout << s.tellp() << 'n';
s << 'h';
std::cout << s.tellp() << 'n';
s << "ello, world ";
std::cout << s.tellp() << 'n';
s << 3.14 << 'n';
std::cout << s.tellp() << 'n' << s.str();
}
输出:<>之前011318你好,3.14号世界 相关文章:
- 将值指定给向量(2D)的向量中的某个位置
- 使用Unreal C++获取VR耳机的世界位置/方向
- 写入位置0x0000000C时发生访问冲突
- 如何将两个不同矢量的同一位置的两个元素组合在一起
- GL_SHADERSTORAGE_BUFFER位置是否与其他着色器位置冲突
- 如何使用cudaMallocManaged在指针位置初始化对象?(C++)
- 无法获取webot::PositionSensor对象中位置传感器的值
- 非常量变量只读位置的赋值
- 如何定义更改car类中car位置的方法
- 使用迭代器时如何访问对象在向量中的位置?
- 更改.cpp程序的输入文件中数据的位置会意外更改输出
- 求最大元素位置的分治算法
- 你好。。。id_public变量不应该给出结果为 81 和 86 吗?为什么它为两个派生类占用不同的内存位置?
- 为什么我的点没有在 OpenGL 中绘制鼠标所在的位置?
- 如何将元素添加到向量的字符串位置
- 如何选择在 csv 文件中输出的位置
- 无法打开 fstream C++文件,即使它与 .cpp 位于同一位置
- 如何在特定位置追加 json 文件
- 当我们进行一些操作时,应该使用什么'std::string'或'std::stringstream'?
- 如何跟踪std::stringstream中的当前位置