开发者

after dup2, stream still contains old contents?

so if I do:

dup2(0, backup); // backup stdin
dup2(somefile, 0); // somefile has four lines of co开发者_高级运维ntent
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?


You haven't flushed the stdin buffer. It has buffered up all the lines of somefile even if the underlying file descriptor is restored.


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜