kuixiong
kuixiong

Reputation: 523

what happend when I close the buffer of stdin and ungetc to stdin?

It came into my mind when I was reading a book about programming on linux, I tried it on my computer and the code worked fine, but I just could not understand how it worked like that, hope someone could help me explain it, thanks in advance! my code is as below:

#include <iostream>
#include <cstdio>

using namespace std;

int main() {
    setbuf(stdin, NULL);
    unsigned char ch = 'a';
    unsigned char pch = ungetc(ch, stdin);
    char c = getchar();
    putchar(c);
    return 0;
}

Upvotes: 0

Views: 87

Answers (1)

rici
rici

Reputation: 241901

Regardless of buffer setting, ungetc must always be able to push one character back into the input stream. If you attempt to push more than one character, ungetc may fail. (You should check the return value for failure.)

One character of pushback is guaranteed. If the ungetc function is called too many times on the same stream without an intervening read or file positioning operation on that stream, the operation may fail. (§7.21.7.10/para. 3)

So a single ungetc is valid, even if there is no input buffer.

Upvotes: 1

Related Questions