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

发布于 2025-01-04 16:27:26 字数 529 浏览 3 评论 0原文

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

所以这是我的代码:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

桃气十足 2025-01-11 16:27:26

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

The simplest way to do this would be to duplicate the output descriptor before closing it. You must look at dup.

花想c 2025-01-11 16:27:26

在关闭它之前,我认为您想要 dup() 它。
当你需要它时,你可以 dup() dup。

dup 将始终使用最低描述符

int out = dup(1);
close(1);
int fd = open();
...
close(fd);
dup(out);
close(out);

警告:这是来自内存且未经测试;-)

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

int out = dup(1);
close(1);
int fd = open();
...
close(fd);
dup(out);
close(out);

Warning: this is from memory and untested ;-)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文