Firdavsbek Narzullaev
Firdavsbek Narzullaev

Reputation: 78

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..?!

Upvotes: 1

Views: 1156

Answers (2)

mattn
mattn

Reputation: 7733

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

Upvotes: 7

Curious
Curious

Reputation: 21560

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

Upvotes: 1

Related Questions