hi guys,

working in C using Borland Compiler we can get scan codes of keyboards keys by this code

ch = getch();
  if (ch == 0)
      ch = getch();

   printf("%d",ch);

because when first time getch() is called, it will return the ascii code of the pressing key. when second time it called then it will return the scan code of that pressing key. So when we want to control our program with arrow keys, there ascii codes are 0 but scan codes are different.

Now while working in linux environment using gcc compiler. there is no conio.h header file in it and we have such function getch(). so how can we get the scan code for arrows and functional keys in C using gcc compiler.

Many Thanks

Asif

#include <stdio.h>
#include <termios.h>
#include <unistd.h>
    
        int getch(){
            struct termios oldt,
                           newt;
            int ch;
            tcgetattr( STDIN_FILENO, &oldt );
            newt = oldt;
            newt.c_lflag &= ~( ICANON | ECHO );
            tcsetattr( STDIN_FILENO, TCSANOW, &newt );
            ch = getchar();
            tcsetattr( STDIN_FILENO, TCSANOW, &oldt );
              
            return ch;
        }

It works for me. Enjoy ;)

Hi,
If its ok the character is echoed on the screen, you can very well go for getc(stdin) or getchar() in a while loop with the termminating condition like carriage return or something you want...

This article has been dead for over six months. Start a new discussion instead.