简体   繁体   中英

How to redirect stderr to file without any buffer?

Does anybody know how to redirect stderr into a file without buffering in? if it is possible could you show me a simple code in c++ language for linux (Centos 6) operating system..?!

In C

#include <stdio.h>

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

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

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

Another way to do this is with the following dup2() call

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM