ANSI C 中的无缓冲 I/O
为了教育和编程实践,我想编写一个简单的库,可以处理原始键盘输入,并“实时”输出到终端。
我想尽可能坚持使用ansi C,我只是不知道从哪里开始这样的事情。我已经进行了几次谷歌搜索,99% 的结果都使用库,或者是针对 C++ 的。
我真的很想让它在 Windows 中工作,然后当我有时间时将其移植到 OSX。
For the sake of education, and programming practice, I'd like to write a simple library that can handle raw keyboard input, and output to the terminal in 'real time'.
I'd like to stick with ansi C as much as possible, I just have no idea where to start something like this. I've done several google searches, and 99% of the results use libraries, or are for C++.
I'd really like to get it working in windows, then port it to OSX when I have the time.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
尽可能坚持使用标准 C 是一个好主意,但是仅使用标准 C 就无法完成您所采用的任务。每次从终端获取一个字符的机制本质上是特定于平台的。对于 POSIX 系统 (MacOS X),请查看
< ;termios.h>
标头。旧系统使用各种各样的标头和系统调用来实现类似的效果。您必须决定是否要进行任何特殊字符处理,请记住诸如“行终止”之类的内容可能会出现在行尾并删除迄今为止输入的所有字符。对于 Windows,您需要深入研究 WIN32 API - Unix 和 Windows 之间的代码本质上没有通用性,至少在将“终端”置于逐字符模式的情况下是如此。一旦你有了读取单个字符的机制,你就可以管理通用代码了——也许。
此外,您还需要担心字符和按下的键之间的差异。例如,要在 MacOS X 上输入“ï”,请键入 option-u 和 i。也就是按三个键。
Sticking with Standard C as much as possible is a good idea, but you are not going to get very far with your adopted task using just Standard C. The mechanisms to obtain characters from the terminal one at a time are inherently platform specific. For POSIX systems (MacOS X), look at the
<termios.h>
header. Older systems use a vast variety of headers and system calls to achieve similar effects. You'll have to decide whether you are going to do any special character handling, remembering that things like 'line kill' can appear at the end of the line and zap all the characters entered so far.For Windows, you'll need to delve into the WIN32 API - there is going to be essentially no commonality in the code between Unix and Windows, at least where you put the 'terminal' into character-by-character mode. Once you've got a mechanism to read single characters, you can manage common code - probably.
Also, you'll need to worry about the differences between characters and the keys pressed. For example, to enter 'ï' on MacOS X, you type option-u and i. That's three key presses.
要使用 ANSI C 将开放流设置为非缓冲,您可以执行以下操作:(
参考:C89 4.9.5.6)
但是,之后您就得靠自己了。 :-)
To set an open stream to be non-buffered using ANSI C, you can do this:
(Reference: C89 4.9.5.6)
However, after that you're on your own. :-)
仅使用标准 ISO C 是不可能实现这一点的。但是,您可以尝试使用以下功能:
和相关函数。
不过,最好的选择是使用 ncurses 库。
This is not possible using only standard ISO C. However, you can try using the following:
and related functions.
Your best bet though is to use the
ncurses
library.