Go4Expert (http://www.go4expert.com/)
-   C (http://www.go4expert.com/forums/c/)
-   -   getch() implementation in C (http://www.go4expert.com/forums/getch-implementation-c-t14325/)

ahamed101 3Oct2008 07:07

getch() implementation in C
Hi Everyone,

I know conio.h is not available in Unix. I want to use getch(). Using curses.h needs causes the screen to clear which I don't want.

I found a code snippet (source : internet) using termios, it works, the thing is I need to press enter/or any other key thrice...


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

int mygetch ( void )
  int ch;
  struct termios oldt, newt;

  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;

int main()

        printf("\n Hello World");
        printf("\n Press any key to continue...");

        return 0;

Is there something to do with the terminal settings?... I tried this in FreeBSD, its working fine... but in HP-UX, AIX its not and it is there where I want to use...

Any suggestions on this would be of great help...


xpi0t0s 6Oct2008 15:41

Re: getch() implementation in C
Tested on Linux 2.6.9 and HP-UX 11.11 and there was no problem - program exited with just a single keypress. On AIX 5.2 it took four keypresses to exit.

[...R-ing TFM...] Aha.

ICANON: ... a read request is not satisfied until one of the following conditions is met:
* The minimum number of characters specified by MIN are received.

So I'd guess your problem is that MIN=3 on HPUX/AIX, and mine is that MIN=4 on AIX and 1 on the other two.

ahamed101 6Oct2008 19:41

Re: getch() implementation in C
Hi xpi0t0s,
Is there anyway we can set the MIN value?... And thanks for that info, it was new to me, wasn't aware of that...


xpi0t0s 6Oct2008 19:53

Re: getch() implementation in C
It was new to me too. Part of a programmer's skillset is to be able to find information for themselves, so I recommend you try to solve this one yourself. You have a big hint, which is the info I've already found for you (basically just by Googling "icanon", although I think I first googled "aix tcgetattr").

ahamed101 8Oct2008 22:27

Re: getch() implementation in C
It worked...
newt.c_cc[VMIN] = 1;
newt.c_cc[VTIME] = 0;

That did it...

Thanks a lot everyone...


All times are GMT +5.5. The time now is 13:51.