Unbuffered I/O in ANSI C

对着背影说爱祢 提交于 2019-11-28 01:55:10

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.

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. :-)

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.

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