如何在没有任何缓冲区的情况下将 stderr 重定向到文件?

How to redirect stderr to file without any buffer?

有人知道如何在不缓冲的情况下将 stderr 重定向到文件吗?如果可能的话,你能告诉我一个简单的 C++ 语言代码,用于 linux (Centos 6) 操作系统..?!

在 C

#include <stdio.h>

int
main(int argc, char* argv[]) {
  freopen("file.txt", "w", stderr);

  fprintf(stderr, "output to file\n");
  return 0;
}

在 C++ 中

#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int
main(int argc, char* argv[]) {
  ofstream ofs("file.txt");
  streambuf* oldrdbuf = cerr.rdbuf(ofs.rdbuf());

  cerr << "output to file" << endl;

  cerr.rdbuf(oldrdbuf);
  return 0;
}

另一种方法是使用以下 dup2() 调用

#include <iostream>
#include <stdexcept>
#include <stdio.h>
#include <unistd.h>

using std::cerr;
using std::endl;

int main() {
    auto file_ptr = fopen("out.txt", "w");
    if (!file_ptr) {
        throw std::runtime_error{"Unable to open file"};
    }

    dup2(fileno(file_ptr), fileno(stderr));
    cerr << "Write to stderr" << endl;
    fclose(file_ptr);
}