Question

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?

Was it helpful?

Solution

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

OTHER TIPS

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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top