dup2之后,流仍然包含旧内容?
所以如果我这样做:
dup2(0, backup); // backup stdin
dup2(somefile, 0); // somefile has four lines of content
fgets(...stdin); // consume one line
fgets(....stdin); // consume two lines
dup2(backup, 0); // switch stdin back to keyboard
我现在发现.. stdin 仍然包含我没有消耗的两行。这是为什么?因为无论重定向多少次,都只有一个缓冲区?当我想返回时,如何摆脱剩下的两行,但仍然记得我在 somefile 流中的位置?
so if I do:
dup2(0, backup); // backup stdin
dup2(somefile, 0); // somefile has four lines of content
fgets(...stdin); // consume one line
fgets(....stdin); // consume two lines
dup2(backup, 0); // switch stdin back to keyboard
I am finding at this point.. stdin still contains the two lines I haven't consumed. Why is that? Because there is just one buffer no matter how many times you redirect? How do I get rid of the two lines left but still remember where I was in the somefile stream when I want to go back to it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您还没有刷新标准输入缓冲区。即使底层文件描述符已恢复,它也缓冲了某个文件的所有行。
You haven't flushed the stdin buffer. It has buffered up all the lines of somefile even if the underlying file descriptor is restored.