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

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

在Windows下:

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

在其它平台下:

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

举例说明:

#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;
}

原文链接: https://www.cnblogs.com/DengSchoo/p/12950381.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

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

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/197804

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月12日 下午7:41
下一篇 2023年2月12日 下午7:41

相关推荐