Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use getch from curses without clearing the screen?

Tags:

c

ncurses

curses

I'm learning to program in C and want to be able to type characters into the terminal while my code is running without pressing return. My program works, however when I call initscr(), the screen is cleared - even after calling filter(). The documentation for filter suggests it should disable clearing - however this is not the case for me.

#include <stdio.h>
#include <curses.h>
#include <term.h>

int main(void) {

    int ch;

    filter();
    initscr();
    cbreak();
    noecho();
    keypad(stdscr, TRUE);

    while((ch = getch()) != EOF);

    endwin();

    return 0;
}

Why does the above code still clearr the screen, and what could be done to fix it?

I'm using Debian Lenny (stable) and gnome-terminal if that helps.

like image 989
Chris R Avatar asked Jan 23 '11 03:01

Chris R


2 Answers

You would see your screen cleared in a curses application for one of these reasons:

  • your program calls initscr (which clears the screen) or newterm without first calling filter, or
  • the terminal initialization clears the screen (or makes it appear to clear, by switching to the alternate screen).

In the latter case, you can suppress the alternate screen feature in ncurses by resetting the enter_ca_mode and exit_ca_mode pointers to NULL as done in dialog. Better yet, choose a terminal description which does what you want.

Further reading:

  • Why doesn't the screen clear when running vi? (xterm FAQ)
like image 72
Thomas Dickey Avatar answered Nov 10 '22 12:11

Thomas Dickey


Basically, curses is designed to take over the screen (or window, in the case of a windowed terminal). You can't really mix curses with stdio, and you can't really use curses to just input or output something without messing with the rest of the screen. There are partial workarounds, but you're never really going to be able to make it work the way that it sounds like you want to. Sorry.

I'd suggest either rewriting your program to use curses throughout, or investigating alternatives like readline.

like image 31
William McBrine Avatar answered Nov 10 '22 10:11

William McBrine