简体   繁体   English

如何跟踪写入std :: ostream对象的字节数?

[英]How can I keep track of the number of bytes written to an std::ostream object?

I want to write a bunch of data to an ostream object and return the number of bytes written. 我想将一堆数据写入ostream对象并返回写入的字节数。 For example: 例如:

using namespace std;
size_t writeStuffToStream(ostream &stream)
{
    stream << some_string << some_integer << some_other_arbitrary_object << endl;
    return number_of_bytes_written;
}

There is the obvious workaround of writing everything to a stringstream and getting the byte count out of that, and then writing the stringstream to the stream, but that takes extra time and memory. 有一种很明显的解决方法,就是将所有内容写入stringstream流,并从中stringstream字节数,然后将stringstream流写入流,但这需要额外的时间和内存。

I also realize that if if all the data I wanted to write were preexisting strings, then there would be no problem. 我还意识到,如果我要写入的所有数据都是预先存在的字符串,那么就不会有问题。 It's some_integer and some_other_arbitrary_object that are the problem. 问题是some_integersome_other_arbitrary_object

Use the ostream tellp() method. 使用ostream tellp()方法。

Note that this might fail if the provided ostream does not support positions. 请注意,如果提供的ostream不支持职位,这可能会失败。 In that case you can create a temporary ostringstream to format your data, then extract the string , get its length and send it to the input ostream . 在这种情况下,您可以创建一个临时的ostringstream来格式化数据,然后提取该string ,获取其长度并将其发送到输入ostream

You can probably also write a custom ostream that send to another ostream and count emitted characters. 您可能还可以编写一个自定义的ostream ,将其发送到另一个ostream并计算发出的字符。 I expected to find a virtual method to override in ostream to write just characters, but I did not find it :( You can re-use the stringstream code and replace the buffer writes to writes to an other ostream. string-stream.cc is about 500 lines long, so that's not this bad. 我期望找到一个在ostream中重写的虚拟方法以仅写入字符,但我没有找到它:(您可以重复使用stringstream代码,并替换写入其他ostream的写缓冲区string-stream.cc是大约500行长,所以这还不错。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM