C 2b 2b Ostream Dev Null Key
Internally, its ostream base constructor is passed a pointer to a newly constructed filebuf object (the internal file stream buffer). (2) initialization constructor Constructs an ofstream object, initially associated with the file identified by its first argument ( filename ), open with the mode specified by mode. I combined three different proposals above and one writing directly to /dev/null (so it involves kernel.) Surprisingly the NullStream that got the most votes performed the worst. Here are results for 100,000,000 writes: a) /dev/null: 30 seconds b) NullStream: 50 seconds c) badbit: 16 seconds (the winner in speed, but cannot test for errors!).
C 2b 2b Ostream Dev Null Command
'Bo Peng' <bp***@rice.edu> wrote in message
news:cd**********@joe.rice.edu...
Dear list,
I need to add 'disable output' feature to a bunch of objects thatoutput to ostream (or ofstream). The least intrusive way to do this is pass
them ofstream('/dev/null') but this makes my program less portable.Is there a null ostream built in cpp?
No.
Is it easy to implement one?
Yes. Derive a class from std::streambuf and override the protected
virtual function overflow as follows
int overflow(int c) { return c; }
Then you can use a standard istream and set its stream buffer to an
instance of your streambuf class using rdbuf. Or you can define your
own derived ostream class which automatically uses an an instance of
your streambuf class.
BTW, Daryle Walker has submitted a null_stream class for inclusion in
Boost, which will be reviewed soon. (See
http://groups.yahoo.com/group/boost/files/more_io_4.zip. (You have to
sign up for the boost developers list to access this:
http://www.boost.org/more/mailing_lists.htm#main.) Also, I have
written an Iostreams Library
(http://home.comcast.net/~jturkanis/iostreams/) which allows a null
ostream to be defined as follows:
struct null_sink : boost::io::sink {
void write(const char*, std::streamsize) { }
};
typedef boost::io::stream_facade<null_sink> null_ostream;
Jonathan