Qore Programming Language

  • Increase font size
  • Default font size
  • Decrease font size

getch example

E-mail Print PDF

This script demonstrates the use of the TermIOS class to get and set terminal settings through the File::getTerminalAttributes() and File::setTerminalAttributes() methods.

In the case of this script the stdout constant is used (which is a constant of class File).

#!/usr/bin/env qore

# this gives an example of how to set the terminal mode for
# reading a single character from stdin at a time without
# echoing it

# require all variables to be declared
%require-our

# uses features first found in qore 0.7.2
%requires qore >= 0.7.2

# enable all warnings
%enable-all-warnings

sub main() {
    my $t = new TermIOS();
    # get current terminal attributes for stdin
    stdin.getTerminalAttributes($t);

    # save a copy
    my $orig = $t.copy();

    # restore terminal attributes on exit
    on_exit
	stdin.setTerminalAttributes(TCSADRAIN, $orig);

    # get local flags
    my $lflag = $t.getLFlag();

    # disable canonical input mode (= turn on "raw" mode)
    $lflag &= ~ICANON;

    # turn off echo mode
    $lflag &= ~ECHO;

    # do not check for special input characters (INTR, QUIT, and SUSP)
    $lflag &= ~ISIG;

    # set the new local flags
    $t.setLFlag($lflag);

    # set minimum characters to return on a read
    $t.setCC(VMIN, 1);

    # set character input timer in 0.1 second increments (= no timer)
    $t.setCC(VTIME, 0);

    # make these terminal attributes active
    stdin.setTerminalAttributes(TCSADRAIN, $t);

    # print a message
    stdout.printf("Press any key: ");

    # print out dots every 20ms to show that we're waiting impatiently for data :-)
    while (!stdin.isDataAvailable(20ms)) {
        # print a dot to stdout
	stdout.printf(".");
	# flush output buffers
	stdout.sync();
    }

    # read the character input
    my $c = stdin.read(1);

    # output the character read
    stdout.printf(" GOT: ASCII 0x%02x (%d) '%s'\n", ord($c), ord($c), $c);
}

main();

Last Updated on Saturday, 25 December 2010 19:55