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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM