开发者

How can I understand that the user pressed which keyword?

I am coding a terminal like Linux terminal with C under Linux OS and I need to quit program when the user presses ctrl+D keywords. But I don't know h开发者_开发技巧ow to understand that the user pressed these keywords. Thanks for your helping.

I'm getting inputs with fgets()


Ctrl+D is end-of-file. In that case, fgets() will return a null pointer.

So, your program's main loop can probably look something like this:

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

Note that this only works for simple buffered input. For information on lower-level keyboard handling, check out http://tldp.org/HOWTO/Keyboard-and-Console-HOWTO.html


Here is a small example, how to read individual keypresses from a terminal keyboard:

#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);
}

Better to know how a terminal sends keystrokes before you start using ncurses to handle terminal I/O.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜