在 C 中重定向 stdout 时的奇怪行为

发布于 2024-12-25 17:02:15 字数 1078 浏览 5 评论 0原文

我正在尝试将 stdout 重定向到一个文件,然后将其恢复到 C 中的原始状态,但我面临以下奇怪的问题 - 以下代码段成功写入
在标准输出中
在标准输出中
在 stdout 和 in file 各自文件中都可以。

#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#define STDOUT 1
int main(int argc, char* argv[]){
    printf("in stdout \n");
    int old_out = dup(STDOUT);
    close(STDOUT);
    int fd = open("./redirected",O_CREAT|O_RDWR|O_TRUNC,0777);
    printf("in file \n");
    close(fd);
    dup(old_out);
    printf("in stdout\n");
    return EXIT_SUCCESS;
}

但是,删除主函数的第一行:

#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#define STDOUT 1
int main(int argc, char* argv[]){
    int old_out = dup(STDOUT);
    close(STDOUT);
    int fd = open("./redirected",O_CREAT|O_RDWR|O_TRUNC,0777);
    printf("in file \n");
    close(fd);
    dup(old_out);
    printf("in stdout\n");
    return EXIT_SUCCESS;
}

导致 在文件中
在标准输出中
被写入标准输出并且文件中没有写入任何内容。我想知道这是怎么发生的?感谢您的任何帮助。

I'm trying to redirect stdout to a file and then restore it back to original in C, but I'm facing the following strange issue - the following piece of code succesfully writes
in stdout
in stdout
in stdout and in file in the respective file which is all OK.

#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#define STDOUT 1
int main(int argc, char* argv[]){
    printf("in stdout \n");
    int old_out = dup(STDOUT);
    close(STDOUT);
    int fd = open("./redirected",O_CREAT|O_RDWR|O_TRUNC,0777);
    printf("in file \n");
    close(fd);
    dup(old_out);
    printf("in stdout\n");
    return EXIT_SUCCESS;
}

However, removing the first row of my main function:

#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#define STDOUT 1
int main(int argc, char* argv[]){
    int old_out = dup(STDOUT);
    close(STDOUT);
    int fd = open("./redirected",O_CREAT|O_RDWR|O_TRUNC,0777);
    printf("in file \n");
    close(fd);
    dup(old_out);
    printf("in stdout\n");
    return EXIT_SUCCESS;
}

leads to
in file
in stdout
being written on stdout and nothing being written in the file. I wonder how this happened? Thanks for any help.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(1

子栖 2025-01-01 17:02:15

这是一个缓冲问题。在重新安装 stdout 之前,您写入“文件中”的缓冲区不会刷新,因此输出将转到 stdout 而不是文件。添加 fflush(stdout); 在这里修复了它。

It's a buffering issue. The buffer you write "in file" to isn't flushed before stdout is reinstalled, so the output goes to stdout and not to the file. Adding fflush(stdout); fixed it here.

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