c - 有什么办法可以查看 stdin 缓冲区吗?

标签 c buffer stdin peek

我们知道 stdin 默认情况下是一个缓冲输入;证明是使用任何在 stdin 上“留下数据”的机制,例如 scanf():

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

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

10 当然是换行...

我一直很好奇,有没有什么方法可以“窥视”stdin 缓冲区而不删除那里可能存在的任何内容?

编辑
一个更好的例子可能是:

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

输入“at.ct”后,现在我在 stdin 上留下了“数据”(ct\n),而不仅仅是一个换行符。

最佳答案

可移植性地,您可以使用 getchar() 获取输入流中的下一个字符,然后使用 ungetc() 将其推回,这会导致一种状态该角色未从流中删除。

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.

标准只保证一个字符的pushback,但通常情况下,你可以pushback更多。

如其他答案中所述。实际上,如果您使用 setvbuf 提供自己的缓冲区,您几乎肯定可以查看缓冲区,尽管这并非没有问题:

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

这留下了可能根本不使用提供的缓冲区的可能性。

The contents of the array at any time are indeterminate.

这意味着您无法保证缓冲区的内容反射(reflect)了实际输入(如果我们挑剔的话,如果它具有自动存储持续时间,它会导致使用缓冲区未定义的行为)。

然而,在实践中,主要问题是找出缓冲区中缓冲输入中尚未使用的部分的开始位置和结束位置。

关于c - 有什么办法可以查看 stdin 缓冲区吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13993742/

相关文章:

c - 汇编编译器是如何编程的

c - 缓冲区溢出 - linux 64bit

javascript - 如何将二进制缓冲区保存到nodejs中的png文件?

perl - 为什么Programming Perl中 "7.2.39 IPC::Open2"所示的程序居然结束了?

perl - 如何确定STDIN是否已连接到Perl中的终端?

c - ARM 设备上的 "undefined behaviour"

c++ - 如何在不使用 dbghelp.dll 的情况下在 Windows 上获取堆栈跟踪?

c - c 中嵌入的汇编代码为 cmp 提供了不正确的操作数类型错误

c - 如何从 PCM 获取缓冲区?

c - Linux C 选择 : piping echo to input works, 但从键盘读取却没有?