• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1156
  • Last Modified:

programming a menu(termios,getch)

I tried to write a simple menu program under linux in cpp. But then
i realized that there is no conio.h under linux. So actuali I am
trying to find a replacement for that simple function (getch) from borlanc Cpp. I can't read the keybord (the directional keys anyway)I heard that using termios.h could solve my problem but the man page is not that helpfull. I would like it to be as simple as possible.
0
Xumxum
Asked:
Xumxum
  • 2
1 Solution
 
dimitryCommented:
There is no getch() function but it can be implemented for example next way:

#include <stdio.h>
#include <termios.h>
#include <term.h>
#include <curses.h>
#include <unistd.h>
/*-------------------------------------------------------*/
static struct termios initial_settings, new_settings;
static int peek_character = -1;
/*-------------------------------------------------------*/
void init_keyboard()
{
  tcgetattr( 0, &initial_settings );
  new_settings = initial_settings;
  new_settings.c_lflag &= ~ICANON;
  new_settings.c_lflag &= ~ECHO;
  new_settings.c_lflag &= ~ISIG;
  new_settings.c_cc[VMIN] = 1;
  new_settings.c_cc[VTIME] = 0;
  tcsetattr( 0, TCSANOW, &new_settings );
}

void close_keyboard()
{
  tcsetattr( 0, TCSANOW, &initial_settings );
}

int kbhit()
{
  char ch;
  int nread;
 
  if( peek_character != -1 )
    return( 1 );
  new_settings.c_cc[VMIN] = 0;
  tcsetattr( 0, TCSANOW, &new_settings );
  nread = read( 0, &ch, 1 );  
  new_settings.c_cc[VMIN] = 1;  
  tcsetattr( 0, TCSANOW, &new_settings );
  if( nread == 1 ) {
    peek_character = ch;
    return( 1 );
  }
  return( 0 );
}

int readch()
{
  char ch;
 
  if( peek_character != -1 ) {
    ch = peek_character;
    peek_character = -1;
    return( ch );
  }
  read( 0, &ch, 1 );
  return( ch );
}

int main()
{
 init_keyboard();
.....
 readch();         <---- getch()
.....
 close_keyboard();
}
0
 
dimitryCommented:
Sorry, small mistake...

int getch()
{
  while( !kbhit() ) ;
  return( readch() );
}
0

Featured Post

What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now