freopen函数:回复到原来的流 [英] freopen: reverting back to original stream

查看:190
本文介绍了freopen函数:回复到原来的流的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要向前标准输出到不同的文件分离产生了一些版画和恢复恢复到正常标准输出。

I needed to forward stdout to different files to separate some prints produced and the reverting back to normal stdout.

我用则freopen 切换到这样的文件:

I used freopen to switch to the file in this way:

char name[80];
memset(name, 0, 80);
strcpy(name, "./scripts/asm/");
strcat(name, m_func->m_name->m_value);
strcat(name, ".shasm");
freopen(name, "w", stdout);

和它的实际工作,但在过程结束(介意标准输出在$ p $重定向多次pvious同样的方式),我不能将它恢复到原来的标准输出。我试过如下:

And it actually works, but at the end of the process (mind that stdout is redirected many times in the previous same way) I'm not able to revert it to original stdout. I tried the following:

freopen("/dev/stdout", "w", stdout);

但它似乎没有工作..只是信息我MacOSX上进行开发。

but it doesn't seem to work.. just for information I'm developing on macosx.

我应该怎么办?

在此先感谢

推荐答案

这可以使用的fileno,DUP和dup2调用来实现。我已经试过这在Linux上不知道这是否会在Mac上工作,但我相信你会得到一些同等功能为您的设置。看看这个样本code为你工作。对不起,在code缺乏的错误处理。 :)

This can be achieved using fileno, dup and dup2 calls. I have tried this on linux not sure whether this will work on mac but I am sure you will get some equivalent functions for your setup. See if this sample code works for you. Sorry for lack of error-handling in the code. :)

    #include <stdio.h>

    main()
    {
        int    fd;
        fpos_t pos;

        printf("stdout, ");

        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");
    }

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

这篇关于freopen函数:回复到原来的流的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆