在 C 中重定向 stdout 时的奇怪行为
我正在尝试将 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 writesin 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 toin file
in stdout
being written on stdout and nothing being written in the file. I wonder how this happened? Thanks for any help.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这是一个缓冲问题。在重新安装 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.