Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I port this program from conio to curses?

I wrote this simple program on Windows. Since Windows has conio, it worked just fine.

#include <stdio.h>
#include <conio.h>

int main()
{
    char input;

    for(;;)
    {
        if(kbhit())
        {
            input = getch();
            printf("%c", input);
        }
    }
}    

Now I want to port it to Linux, and curses/ncurses seems like the right way to do it. How would I accomplish the same using those libraries in place of conio?

like image 723
Veselin Romić Avatar asked Sep 03 '12 12:09

Veselin Romić


1 Answers

#include <stdio.h>
#include <ncurses.h>

int main(int argc, char *argv)
{
    char input;

    initscr(); // entering ncurses mode
    raw();     // CTRL-C and others do not generate signals
    noecho();  // pressed symbols wont be printed to screen
    cbreak();  // disable line buffering
    while (1) {
        erase();
        mvprintw(1,0, "Enter symbol, please");
        input = getch();
        mvprintw(2,0, "You have entered %c", input);
        getch(); // press any key to continue
    }
    endwin(); // leaving ncurses mode    
    return 0;
}

When building your program do not forget to link with ncurses lib (-L lncurses) flag to gcc

gcc -g -o sample sample.c -L lncurses

And here you can see kbhit() implementation for linux.

like image 199
Xentatt Avatar answered Oct 23 '22 08:10

Xentatt