Unbuffered I/O in ANSI C

て烟熏妆下的殇ゞ 提交于 2019-11-26 23:36:49

问题


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.


回答1:


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.




回答2:


To set an open stream to be non-buffered using ANSI C, you can do this:

#include <stdio.h>
if (setvbuf(fd, NULL, _IONBF, 0) == 0)
  printf("Set stream to unbuffered mode\n");

(Reference: C89 4.9.5.6)

However, after that you're on your own. :-)




回答3:


This is not possible using only standard ISO C. However, you can try using the following:

#include <stdio.h>
void setbuf(FILE * restrict stream, char * restrict buf); 

and related functions.

Your best bet though is to use the ncurses library.



来源:https://stackoverflow.com/questions/1647927/unbuffered-i-o-in-ansi-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!