调用fclose(stdout);后,如何再开启标准输出

    技术2022-05-11  161

    请看程序

    #include <string.h> #include <stdio.h>

    int main(void) {    int i;   /* redirect standard output to a file */    if (freopen("name.txt", "w", stdout)        == NULL)       fprintf(stderr, "error redirectingstdout/n");

       /* this output will go to a file */    printf("This will go into a file.");       /* close the standard output stream */       fclose(stdout);   scanf( "%d", &i) ;   printf("%d",i);  //这个语句没有用了,不能显示i的值了

       return 0; }   解决方法:

    在对stdout进行重定向之前拷贝一份stdout对应的文件描述符:

    int fd_stdout = dup( fileno(stdout) );

    在fclose(stdout)之后如果想恢复原来的stdout的话:

    fdopen( fd_stdout, "w" );


    最新回复(0)