freopen函数stdout和控制台 [英] freopen stdout and console

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

问题描述

由于以下功能:

freopen("file.txt","w",stdout);

标准输出重定向到一个文件,我怎么做起来很标准输出重定向返回到控制台?

Redirects stdout into a file, how do I make it so stdout redirects back into the console?

我会注意到的,是有类似这样的其他问题, ,但他们对Linux / POSIX。我使用Windows。

I will note, yes there are other questions similar to this, but they are about linux/posix. I'm using windows.

您不能分配到stdout,这抵消一组依赖于它的解决方案。
DUP和dup2()不属于本土的窗口中,抵消了另一套。至于说,POSIX函数不适用(除非你fdopen())。

You can't assigned to stdout, which nullifies one set of solutions that rely on it. dup and dup2() are not native to windows, nullifying the other set. As said, posix functions don't apply (unless you count fdopen()).

推荐答案

您应该能够使用的 _dup 来做到这一点。

You should be able to use _dup to do this

像这样的东西应该工作(或者你可以preFER的 _dup 文档中列出的例子):

Something like this should work (or you may prefer the example listed in the _dup documentation):

#include <io.h>
#include <stdio.h>

...
{
    int stdout_dupfd;
    FILE *temp_out;

    /* duplicate stdout */
    stdout_dupfd = _dup(1);

    temp_out = fopen("file.txt", "w");

    /* replace stdout with our output fd */
    _dup2(_fileno(temp_out), 1);
    /* output something... */
    printf("Woot!\n");
    /* flush output so it goes to our file */
    fflush(stdout);
    fclose(temp_out);
    /* Now restore stdout */
    _dup2(stdout_dupfd, 1);
    _close(stdout_dupfd);
}

这篇关于freopen函数stdout和控制台的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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