Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C library function to check the keypress from keyboard( in linux ) [closed]

Tags:

c

Is there any C library function to check the keypress from keyboard( I am working on linux machine ).

like image 736
user3035481 Avatar asked Dec 03 '13 11:12

user3035481


People also ask

How to detect keypress in c linux?

You can use getchar() or getc(stdin) , these are standard functions in C. They echo the character to the terminal that was pressed. getchar() function will wait for input from keyboard, if we don't press any key it will continue to be in the same state and program execution stops there itself untill we press a key.

How do you see what keys are being pressed on keyboard?

The Windows on-screen keyboard is a program included in Windows that shows an on-screen keyboard to test modifier keys and other special keys. For example, when pressing the Alt , Ctrl , or Shift key, the On-Screen Keyboard highlights the keys as pressed.


1 Answers

getchar() from the Header file stdio.h returns the next character from stdin. That's probably what you're searching for.

The following code will output the first char from the stdin stream:

#include <stdio.h>
int main (int argc, char **argv){
  char c = getchar();
  printf("Char: %c", c);
  return 0;
}

There are also other functions available to do this without blocking i.e. kbhit() and getch() in conio.h. But the header file conio.h is non-standard and probably not available on your platform if you are using linux.

So you have 2 options:

1.) Using the library ncurses you can use i.e. the function timeout() to define an timeout for the getch() function like this:

initscr();
timeout(1000);
char c = getch();
endwin();
printf("Char: %c\n", c);

2.) Implement kbhit() by yourself without using ncurses. There is a great expanation here to do so. You would have to measure time by yourself and looping until your timeout is reached. To measure time in C, there are plenty threads here on stackoverflow - you just have to search for it. Then your code would look like this:

while(pastTime() < YOUR_TIMING_CONSTRAINT){
  if (kbhit()){
    char c = fgetc(stdin);
    printf("Char: %c\n", c);
  }
}
like image 84
Constantin Avatar answered Sep 22 '22 07:09

Constantin