getch() implementation in C

ahamed101's Avatar, Join Date: Sep 2008
Go4Expert Member
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...

Code:
#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...");
	mygetch();

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

Regards,
Ahamed
xpi0t0s's Avatar, Join Date: Aug 2004
Mentor
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's Avatar, Join Date: Sep 2008
Go4Expert Member
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...

Regards,
Ahamed.
xpi0t0s's Avatar, Join Date: Aug 2004
Mentor
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's Avatar, Join Date: Sep 2008
Go4Expert Member
It worked...
newt.c_cc[VMIN] = 1;
newt.c_cc[VTIME] = 0;

That did it...

Thanks a lot everyone...

Regards,
Ahamed.