Thursday, February 28, 2013

Termios to get Ncurses cbreak without Ncurses

In my C++ program I wanted to capture keypresses in command line without waiting for newline/enter being entered.
Ncurses has a command cbreak() which does this, but I wasn't using Ncurses.

I finally found termios.h library and tcgetattr()/tcsetattr() commands:


#include <termios.h>

int main(int argc, char* argv[])

{
    struct termios m_old_term_config;
    struct termios m_new_term_config;

    // Get current terminal configuration
    tcgetattr(STDIN_FILENO, &m_old_term_config);

    // Make a copy to restore later
    m_new_term_config = m_old_term_config;

    // Disable line by line input and echo
    m_new_term_config.c_lflag &= ~(ICANON | ECHO);

    // Or only disable line by line input
    //m_new_term_config.c_lflag &= ~ICANON

    tcsetattr(STDIN_FILENO, TCSANOW, &m_new_term_config);

    /* Run program without line by line input and echoing  */

    // Restore old terminal configuration when closing program
    tcsetattr(STDIN_FILENO, TCSANOW, &m_old_term_config);
}



Sources: http://linux.die.net/man/3/termios
http://en.wikibooks.org/wiki/Serial_Programming/termios