redirect stdout and back to screen

  1. fprintf(stdout, "This will go to the terminal.\n");
  2. //Save position of current standard output
  3. fpos_t pos;
  4. fgetpos(stdout, &pos);
  5. int fd = dup(fileno(stdout));
  6. freopen("/tmp/somefile.txt", "w", stdout);
  7. fprintf(stdout, "This will go to the file /tmp/somefile.txt.\n");
  8. //Flush stdout so any buffered messages are delivered
  9. fflush(stdout);
  10. //Close file and restore standard output to stdout - which should be the terminal
  11. dup2(fd, fileno(stdout));
  12. close(fd);
  13. clearerr(stdout);
  14. fsetpos(stdout, &pos);
  15. fprintf(stdout, "This will go to the terminal.\n");
發佈了53 篇原創文章 · 獲贊 17 · 訪問量 48萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章