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

问题描述 投票:0回答:2

有没有人知道如何在不缓冲的情况下将stderr重定向到文件中?如果有可能你能用Linux(Centos 6)操作系统的c ++语言向我展示一个简单的代码..?!

c++ linux centos6
2个回答
5
投票

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

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);
}
© www.soinside.com 2019 - 2024. All rights reserved.