`
yaojingguo
  • 浏览: 202796 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

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>
分享到:
评论
2 楼 yaojingguo 2010-08-23  
Hi, Liang Liang

Thanks for the information
1 楼 fuliang 2009-12-16  
使用gcc编译.cpp,可以使用-lstdc++选项,这样gcc就可以链接了,比如:gcc -o test.out test.cpp -lstdc++

相关推荐

Global site tag (gtag.js) - Google Analytics