Linux redirect the stdout to a file

   1: int save_out = dup(fileno(stdout));//backup stdout
   2: int out = open("cout.log", O_RDWR|O_CREAT|O_APPEND, 0600);
   3: int  nRet;
   4: fflush(stdout);
   5: dup2(out, fileno(stdout));// redirect stdout to out
   8: printf("Hello world!");
  10: fflush(stdout);close(out);close(stdout);
  11: dup2(save_out, fileno(stdout));//return the backup
  12: close(save_out);

include the header file #include <fcntl.h>

原文地址:https://www.cnblogs.com/dorothychai/p/3278704.html