c++ - freopen : reverting back to original stream

标签 c++ c stdio

我需要将 stdout 转发到不同的文件以分离生成的一些打印件并恢复到正常的 stdout。

我用freopen这样切换到文件:

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

它确实有效,但在过程结束时(请注意,stdout 以以前相同的方式多次重定向)我无法将其恢复为原始 stdout。我尝试了以下方法:

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

但它似乎不起作用.. 仅供我在 macosx 上开发的信息。

我该怎么办?

提前致谢

最佳答案

这可以使用 fileno、dup 和 dup2 调用来实现。我已经在 linux 上试过了,不确定这是否适用于 mac,但我相信你会为你的设置获得一些等效的功能。查看此示例代码是否适合您。抱歉,代码中缺少错误处理。 :)

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

关于c++ - freopen : reverting back to original stream,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1673764/

相关文章:

c++ - 扫描目录以查找并打开文件

C正在将字符串转换为十六进制

c - 如果没有任何改变来终止 while 循环,则 while 循环不起作用

在 C 中创建一个空心矩形而不添加空格作为其元素

c++ - 函数定义为限定 id

c++ - 如何制作可复制的 boost::signal?

c++ - NMAKE : fatal error U1077: cl. exe 和 nmake.exe 返回代码 '0x2'

c++ - 没有 IDE 的 Arduino DUE 编程 (Linux)

c - scanf() - 获取字段计数并检查 EOF

c - 如果一个 C 函数被调用两次,它会创建一个在函数中声明的变量两次吗?