本文参考了《C专家编程》。在此基础上添加了部分注释。
在UNIX中,默认整行读入一起处理。有两种方法可以实现逐字符读入,即不按回车就可以从中断读入一个字符。
方法一:使用stty程序——阻塞读入,如果中断没有字符输入进程就一直等待。
#include <stdio.h> int main() { char ch; system("stty raw"); //开启一次读一个字符的模式 ch = getchar(); printf("it's %c\n",ch); system("stty cooked"); //关闭一次读一个字符的模式 return 0; }
方法二:使用ioctl()实现——非阻塞读入,轮询形式,只有当一个字符等待被读入时才进行读取。
#include <stdio.h> #include <sys/ioctl.h> int main() { int i,num; char ch = ' '; system("stty raw -echo"); //-echo表示按键时并不回显在屏幕 printf("enter 'q' to quit\n"); for(i = 0 ;ch != 'q'; i++) //一直轮询 { ioctl(0,FIONREAD,&num); //获得从终端可以读取的字符的计数值 if(num > 0) //如果>0,即终端有字符可以读入的话则读入 { ch = getchar(); printf("\n got %c on iteration %d",ch,i); } } system("stty cooked echo"); //关闭一次一字符模式并恢复按键时屏幕的回显功能 }