C: how to redirect stderr from System-command to stdout or file?

otto picture otto · Jun 11, 2010 · Viewed 22.2k times · Source

The shell command $ avrdude -c usbtiny outputs text to stderr. I cannot read it with commmands such as head-less-more cos it is not stdout. I want the text to stdout or to a file. How can I do it in C? I have tried to solve the problem by my last question but still unsolved.

Answer

Dusty picture Dusty · Jun 11, 2010

I've not tried something like this in OpenBSD, but in at least a few *nix-like systems, you can do this using dup2.

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

int main(void) {  

  fprintf(stderr, "This goes to stderr\n");

  dup2(1, 2);  //redirects stderr to stdout below this line.

  fprintf(stderr, "This goes to stdout\n");
}