如何恢复标准输出的文件描述符?

sau*_*abh 0 c linux printf file-descriptor system-calls

我需要帮助来理解文件描述符

所以这是我的代码:

int main()
{
    char ch;
    close(1);
    //now opening a file so that it gets the lowest possible fd i.e. 1
    int fd=open("txt",O_RDWR);
    //check..
    printf("first printtf is executed\n");
    scanf("%c",&ch);
    printf("ur value is %c\n",ch);

    printf("second printf is executed\n");
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

在上面的程序中,我尝试将 的输出重定向printftxt文件而不是标准输出,即终端。但是如何恢复标准输出文件描述符,以便printf在第二种情况下再次正常工作,即第二个printtf应该只向终端提供输出..

pra*_*kar 5

最简单的方法是在关闭之前复制输出描述符。你必须看看dup