开发者

switch between writing to file and stdout

开发者 https://www.devze.com 2023-03-31 16:23 出处:网络
I want to switch between writing to the file and to the stdout I can\'t use fprintf, but only printf and freopen

I want to switch between writing to the file and to the stdout I can't use fprintf, but only printf and freopen something like this:

for(size_t i;i<100;++i)
{
     if(i%2)
     {
        freopen("tmp","w",stdout);
        printf("%d\n",i);
     }
     else
     {
        //return to write to stdout?
        printf开发者_如何学编程("%d\n",i);
     }
}

How can I return to writing to the stdout?

Update

I write cross-platform application and dup can't be used.


Never use freopen. It cannot achieve what you want, and it's a very dangerous function. If it fails, the only safe thing you can do is immediately terminate the program or ensure that stdout is never accessed again.

There is a way to do what you want on POSIX systems with dup and dup2. It looks something like this:

fflush(stdout);
int old_stdout = dup(1);
int new_stdout = open("whatever", O_WRDONLY|O_CREAT, 0666);
dup2(new_stdout, 1);
close(new_stdout);
/* use new stdout here */
fflush(stdout);
dup2(old_stdout, 1);
close(old_stdout);


You need to dup the file descriptors, and reopen to the open descriptor. Why can't you use fprintf? (Is this homework?)

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号