Jimm
Jimm

Reputation: 8505

How redirect std::ostream to a file or /dev/null in c++ and linux

I have a c++ application, which contains large amount of std::cout. It runs on linux 2.6.x. I need to test the performance of the application, so i am thinking of redirecting the std::cout to /dev/null. In C, i could simply use dup2. Is there an equivalent in c++ to redirect std::ostream to a file or /dev/null?

Upvotes: 1

Views: 2393

Answers (3)

Potatoswatter
Potatoswatter

Reputation: 137870

The dup2 trick will still work in C++, since just like <stdio.h>, <iostream> is just a buffering layer atop the UNIX system calls.

You can also do this at the C++ level by disconnecting the buffer from std::cout:

std::cout.rdbuf( NULL );

Besides severing the relationship between std::cout and any actual output device, this will set the std::ios::badbit flag which will prevent any output conversions (e.g. numbers to text) from occuring. Performance should be much better than with the filesystem-level hack.

Upvotes: 6

Eric
Eric

Reputation: 19873

An alternative way would be to symlink your file to /dev/null.

% ln -s /dev/null core
% ls -l core
lrwx-xr-x  1 john users 9 Nov 18 12:26 core -> /dev/null

To truly test your program speed however I would suggest to comment out the writes to your file and calculate the execution time difference, because writing to /dev/null might have different overhead than writing to a normal file.

Upvotes: 0

Ben Jackson
Ben Jackson

Reputation: 93860

You can do the exact same thing in C++. Both C and C++ both rely on the underlying operating system for IO, and redirecting fd 1 will affect std::cout just like it affects stdout.

(of course for testing you can just run the command with > /dev/null on the command line...)

Upvotes: 3

Related Questions