如何恢复标准输出的文件描述符?
我需要帮助来理解文件描述符
所以这是我的代码:
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;
}
在上面的程序中,我尝试将 printf
的输出重定向到 txt
文件而不是标准输出,即终端。 但是如何恢复标准输出文件描述符,以便 printf 在第二种情况下再次正常工作,即第二个 printtf 应该仅向终端提供输出。
I need help to understand the file descriptors
So here is my code:
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;
}
in the above program, I tried to redirect the output of printf
to the txt
file rather than the standard output, i.e. the terminal.
But how to restore the standard output file descriptor so that the printf
again works as normal for the second case, i.e the second printtf
should give output to the terminal only..
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
最简单的方法是在关闭输出描述符之前复制它。您必须查看dup。
The simplest way to do this would be to duplicate the output descriptor before closing it. You must look at dup.
在关闭它之前,我认为您想要 dup() 它。
当你需要它时,你可以 dup() dup。
dup 将始终使用最低描述符
警告:这是来自内存且未经测试;-)
Before you close it I think you want to dup() it.
When you need it back, you can dup() the dup.
dup will always use the lowest descriptor
Warning: this is from memory and untested ;-)