C/C++使用freopen重定向到文件后重新回到控制台

在操作系统中,命令行控制台(即键盘或者显示器)被视为一2文件,既然是文件,那么就有“文件名”。由于历史原因,命令行控制台文件在DOS操作系统和Windows操作系统中的文件名为"CON",在其它的操作系统(例如Unix、Linux、Mac OS X、Android等等)中的文件名为"/dev/tty"。

在Windows下:

freopen("CON", "w", stdout);

在其它平台下:

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

举例说明:

#include<stdio.h>
#include<stdlib.h>
int main()
{
    FILE *stream;
    if ((stream = freopen("file.txt", "w", stdout)) == NULL)
        exit(-1);
    printf("this is stdout output\n");
    stream = freopen("CON","w",stdout);
    /*stdout是向程序的末尾的控制台重定向*/
    printf("And now back to the console once again\n");
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/DengSchoo/p/12950381.html