2

I want to write a bunch of data to an ostream object and return the number of bytes written. 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.

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.

1
  • 1
    you can chain streambuf objects, so you can derive a counting streambuf from std::streambuf. in it, delegate operations to the original streambuf after recording the counter info. There's a nice tutorial here: mr-edd.co.uk/blog/beginners_guide_streambuf Commented Dec 15, 2016 at 21:50

1 Answer 1

2

Use the ostream tellp() method.

Note that this might fail if the provided ostream does not support positions. 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.

You can probably also write a custom ostream that send to another ostream and count emitted characters. 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.

Sign up to request clarification or add additional context in comments.

1 Comment

Yeah, I'm a little put off by the fact that tellp() is not guaranteed to work for all objects. And I already mentioned that I don't want to have to create an intermediate stringstream. How would I create a custom ostream that can count the bytes written, if I can't count the bytes written in the first place?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.