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.
我正在尝试将stdout重定向到一个文件,然后在C中将其恢复为原始文件,但我面临以下奇怪的问题 - 下面的一段代码成功地在stdout中的stdout和相应文件的文件中写入stdout哪一切都好。
#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.
导致stdout中的文件写入stdout并且文件中没有写入任何内容。我想知道这是怎么发生的?谢谢你的帮助。
1 个解决方案
#1
4
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.
这是一个缓冲问题。您在“文件”中写入的缓冲区在重新安装stdout之前未刷新,因此输出将转到stdout而不是文件。添加fflush(stdout);把它固定在这里。
#1
4
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.
这是一个缓冲问题。您在“文件”中写入的缓冲区在重新安装stdout之前未刷新,因此输出将转到stdout而不是文件。添加fflush(stdout);把它固定在这里。