这个标准输出重定向是如何工作的?
下面的代码将 stdout 重定向到文件 fname &然后重定向回原始标准输出。它对我来说效果很好。 但我无法理解它实际上是如何工作的。如果有人能帮助我理解,我将不胜感激。
printf("\n This is console");
fflush(stdout);
fgetpos(stdout, &pos);
fd = dup(fileno(stdout));
freopen(fname, "a+", stdout);
printf("inside file op");
fflush(stdout);
dup2(fd,fileno(stdout));
close(fd);
clearerr(stdout);
fsetpos(stdout, &pos);
printf("\nBack to Console");
Code below redirects stdout to a file fname & then redirects back to original stdout. It works fine for me.
But I am not able to understand how it actually works. If anyone can help me understand I will appreiciate it.
printf("\n This is console");
fflush(stdout);
fgetpos(stdout, &pos);
fd = dup(fileno(stdout));
freopen(fname, "a+", stdout);
printf("inside file op");
fflush(stdout);
dup2(fd,fileno(stdout));
close(fd);
clearerr(stdout);
fsetpos(stdout, &pos);
printf("\nBack to Console");
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
让我们逐行浏览一下。第一行向
stdout
打印一些内容:然后刷新
stdout
,以便缓冲区中的所有剩余数据都发送到stdout
并且不会得到与文件数据混合:现在我们将自己的当前位置存储在
stdout
中,否则如果stdout
已经定向到文件,我们可能(?)覆盖前面的部分它的。现在我们克隆当前
stdout
的文件描述符。由于我们要更改stdout
指向的位置,因此需要保留原始文件的副本:现在我们已保留所有内容,我们可以重新打开
stdout
作为文件:此时,
stdout
已被重定向到该文件。我们现在可以打印到它:现在我们已经完成了打印到文件。我们需要刷新
stdout
(现在是文件),这样它就不会与正常的stdout
数据混淆:之后,我们克隆原始的
stdout< /code> 文件描述符覆盖当前
stdout
描述符。克隆的文件现在可以关闭:
我不太确定为什么会出现这种情况,但这会清除写入文件时发生的任何错误:
现在我们恢复在
stdout
中的位置。同样,据我所知,这仅在最初重定向到文件时才有用:现在我们回到原始的 stdout,因此我们可以再次打印:
Let's go through it line by line. The first line prints something to
stdout
:Then it flushes
stdout
so all the remaining data in the buffer gets sent tostdout
and won't get mixed up with the file data:Now we store the current position of ourselves in
stdout
because otherwise ifstdout
was already directed to a file, we might (?) overwrite earlier parts of it.Now we clone the file descriptor of what's currently
stdout
. Since we're about to change wherestdout
points to, we need to keep a copy of the original:Now that we have everything preserved, we can reopen
stdout
as the file:At this point,
stdout
has been redirected to the file. We can now print to it:Now we're done printing to the file. We need to flush
stdout
(now the file) so it doesn't get mixed up with the normalstdout
data:After that, we clone the original
stdout
file descriptor over the currentstdout
descriptor.The cloned one can be closed now:
I'm not quite sure why this is here but this clears any errors that occurred writing to the file:
Now we restore our position in
stdout
. Again, as far as I know, this is only useful if it was originally redirected to a file:Now we're back to the original
stdout
, so we can print again: