Redirect and restore stdout in C

After a lot of googling, I find the following code. It works.

 

#include <stdio.h>

void f() {
  printf("stdout in f()");
}

main() {
  int fd;
  fpos_t pos;

  printf("stdout, ");

  // redriect
  fflush(stdout);
  fgetpos(stdout, &pos);
  fd = dup(fileno(stdout));
  freopen("stdout.out", "w", stdout);

  f();

  fflush(stdout);
  dup2(fd, fileno(stdout));
  close(fd);
  clearerr(stdout);
  fsetpos(stdout, &pos);        /* for C9X */

  printf("stdout again\n");
}

 You can compile it with gcc. If you save it in a file with .cpp as extenstion name and compile the cpp file with g++, you need to include unistd.h. Add the following additional line.

#include <unistd.h>

你可能感兴趣的:(C++,c,C#,F#,gcc)