Home > Blockchain >  How do I redirect stderr to /dev/null in C ?
How do I redirect stderr to /dev/null in C ?

Time:04-17

#include <cstddef>
#include <iostream>
#include <fstream>
#include <string>
using namespace std;


int main() {
   
    //read the lines from the piped file using cin
    string response;
    int i = 0;
    while (getline(cin, response)) {
        //if the response is empty, stop
        if (response.empty()) {
            break;
        }
        
        //Write each odd line (1,3, etc..) to stderr (cerr) 
        //Write each even line (2,4. etc..) to stdout (cout) 
        if (i % 2 != 1) { //send odd to stderr
            cerr << "err: " << response << endl;
        }
        else { //send even to stdout
            cout << "out: " << response << endl;
        }
        i  ;

    }

        
    return 0;
}

I want to redirect stderr to /dev/null, how would I go about doing so? I'm new to C and trying to learn by practicing, however, I'm not easily able to find an answer that fits my existing program.

CodePudding user response:

Besides the excellent commentary above, it is pretty easy to make a “null” streambuf sink in C .

#include <iostream>

struct null_streambuf: public std::streambuf
{
  using int_type = std::streambuf::int_type;
  using traits   = std::streambuf::traits_type;

  virtual int_type overflow( int_type value ) override
  {
    return value;
  }
};

To use it, just set the rdbuf:

int main()
{
  std::cerr.rdbuf( new null_streambuf );
  std::cerr << "Does not print!\n";
}

If you wish to be able to turn it off and on, you will have to remember the original and restore it, not forgetting to delete the new null_streambuf.

int main()
{
  std::cerr << "Prints!\n";

  auto original_cerr_streambuf = std::cerr.rdbuf( new null_streambuf );
  std::cerr << "Does not print.\n";

  delete std::cerr.rdbuf( original_cerr_streambuf );
  std::cerr << "Prints again!\n";
}

This does have the objective effect of being compiled to code, which I suspect is the advantage you are looking for: the ability to dynamically enable and disable diagnostic output.

This is, however, the usual function of a debug build, where you use the DEBUG macro to decide whether or not to compile something (such as error output operations) into the final executable.

Keep in mind that this does not disable output on standard error via other means, but only through cerr.

  • Related