请看程序
#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" );
博客给出一段C语言程序,实现将标准输出重定向到文件,重定向后关闭标准输出流,导致后续无法显示输入值。同时给出解决方法,即在重定向之前拷贝stdout对应的文件描述符,关闭后可通过该描述符恢复原来的stdout。

1854

被折叠的 条评论
为什么被折叠?



