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

Read up on ncurses if you want advanced control of a terminal environment.

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...

Here is a link which could give you some hint!!!

ssharish

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.