我如何理解用户按下了哪个关键字?

时间:2009-12-01 21:47:48

标签: c linux terminal

我在Linux操作系统下使用C编写类似Linux终端的终端,当用户按下ctrl + D关键字时我需要退出程序。但我不知道如何理解用户按下这些关键字。谢谢你的帮助。

我正在使用fgets()

获取输入

2 个答案:

答案 0 :(得分:3)

Ctrl + D是文件结尾。在这种情况下,fgets()将返回空指针。

所以,你的程序的主循环可能看起来像这样:

char buffer[2000];
const char* input = fgets(buffer, sizeof(buffer), stdin);
while (input) {
    do_something_with(input);
    input = fgets(buffer, sizeof(buffer), stdin);
}

请注意,这仅适用于简单的缓冲输入。有关下级键盘处理的信息,请查看http://tldp.org/HOWTO/Keyboard-and-Console-HOWTO.html

答案 1 :(得分:2)

这是一个小例子,如何从终端键盘读取单个按键:

#include <stdio.h>
#include <termios.h> 
#include <unistd.h> 

int main(void){
  struct termios save,raw;
  tcgetattr(0,&save);
  cfmakeraw(&raw); tcsetattr(0,TCSANOW,&raw);
  unsigned char ch;
  do{
    read(0,&ch,1);
    if( ch<32 ) printf("read: Ctrl+%c (%i)\r\n",ch+'@',ch);
    else        printf("read: '%c' (%i)\r\n",ch,ch);
  }while(ch!='q');
  tcsetattr(0,TCSANOW,&save);
}

在开始使用ncurses处理终端I / O之前,最好知道终端如何发送击键。