如何在 C++ 中将 stderr 重定向到 /dev/null?

How do I redirect stderr to /dev/null in C++?

#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;
}

我想将 stderr 重定向到 /dev/null,我该怎么做呢?我是 C++ 的新手,尝试通过练习来学习,但是,我不容易找到适合我现有程序的答案。

除了上面的精彩评论外,在 C++ 中创建一个“空”streambuf 接收器也很容易。

#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;
  }
};

要使用它,只需设置 rdbuf:

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

如果你希望能够关闭和打开它,你将不得不记住原来的并恢复它,不要忘记 delete 新的 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";
}

这确实具有编译为代码的 objective 效果,我怀疑这就是您正在寻找的优势:动态启用和禁用诊断输出的能力。

然而,这是调试构建的常用功能,您可以在其中使用 DEBUG 宏来决定是否将某些内容(例如错误输出操作)编译到最终的可执行文件中。

请记住,这 不会 通过其他方式禁用标准错误输出,但只能通过 cerr.