先关闭stdout,再打开stdout后,结果puts和putchar函数不能正确输出,求指教
目的:测试关闭stdout后重新打开stdout。
存在问题://@ 标记之后的两行输出不正常
代码如下:
- C/C++ code
#include <stdio.h>#include <unistd.h>int main(){ int fd; int tmp; int n; int outfd; outfd = fileno(stdout);// 记录原始的stdout的文件描述符,其实就是1 fd = dup(fileno(stdout));//复制stdout的文件描述符,这是如果只关闭stdout>,并没有真正关闭文件 fclose(stdout); printf("This sentence will not be printed."); dup2(fd, outfd);//重新将outfd关联到默认的标准输出,即终端 close(fd); tmp = fileno(stdout); stdout = fdopen(outfd, "w");//@ puts("puts"); printf("This sentence will be printed.\n"); printf("fd:%d\ttmp:%d\t outfd:%d\n", fd, tmp, outfd); printf("fd:%d\ttmp:%d\t outfd:%d\n", fd, tmp, outfd); return 0;}输出结果:
fd:3tmp:-1 outfd:1
如果将puts和printf函数换成fputs和fprintf函数,就可以输出正常。
如:
- C/C++ code
#include <stdio.h>#include <unistd.h>int main(){ int fd; int tmp; int n; int outfd; outfd = fileno(stdout);// 记录原始的stdout的文件描述符,其实就是1 fd = dup(fileno(stdout));//复制stdout的文件描述符,这是如果只关闭stdout>,并没有真正关闭文件 fclose(stdout); fprintf(stdout,"This sentence will not be printed."); dup2(fd, outfd);//重新将outfd关联到默认的标准输出,即终端 close(fd); tmp = fileno(stdout); stdout = fdopen(outfd, "w");//@ fputs("puts\n",stdout); fprintf(stdout,"This sentence will be printed.\n"); printf("fd:%d\ttmp:%d\t outfd:%d\n", fd, tmp, outfd); return 0;}输出结果:
puts
This sentence will be printed.
fd:3tmp:-1 outfd:1
就是说puts函数不能正常工作,而换成fputs就可以正常工作,求大神!!
[解决办法]
你用的方法不对,要这样用:
- C/C++ code
#include <stdio.h>#include <unistd.h>int main(int argc, char* argv[]){ fclose(stdout); printf("This sentence will not be printed."); freopen("/dev/tty", "w", stdout); puts("puts"); printf("This sentence will be printed.\n"); return 0;}