Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
214 views
in Technique[技术] by (71.8m points)

c - Is there any way to peek at the stdin buffer?

We know that stdin is, by default, a buffered input; the proof of that is in usage of any of the mechanisms that "leave data" on stdin, such as scanf():

int main()
{
    char c[10] = {''};
    scanf("%9s", c);
    printf("%s, and left is: %d
", c, getchar());
    return 0;
}

./a.out
hello
hello, and left is 10

10 being newline of course...

I've always been curious, is there any way to "peek" at the stdin buffer without removing whatever may reside there?

EDIT
A better example might be:

scanf("%9[^.]", c);

With an input of "at.ct", now I have "data" (ct ) left on stdin, not just a newline.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Portably, you can get the next character in the input stream with getchar() and then push it back with ungetc(), which results in a state as if the character wasn't removed from the stream.

The ungetc function pushes the character specified by c (converted to an unsigned char) back onto the input stream pointed to by stream. Pushed-back characters will be returned by subsequent reads on that stream in the reverse order of their pushing.

Only one character of pushback is guaranteed by the standard, but usually, you can push back more.

As mentioned in the other answers resp. the comments there, in practice, you can almost certainly peek at the buffer if you provide your own buffer with setvbuf, although that is not without problems:

If buf is not a null pointer, the array it points to may be used instead of a buffer allocated by the setvbuf function

that leaves the possibility that the provided buffer may not be used at all.

The contents of the array at any time are indeterminate.

that means you have no guarantee that the contents of the buffer reflects the actual input (and it makes using the buffer undefined behaviour if it has automatic storage duration, if we're picky).

However, in practice the principal problem would be finding out where in the buffer the not-yet-consumed part of the buffered input begins and where it ends.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...