Prev | Current Page 1385 | Next

Christopher Negus

"Linux Bible, 2008 Edition: Boot up to Ubuntu, Fedora, KNOPPIX, Debian, openSUSE, and 11 Other Distributions"


To give you an idea of how ncurses works and what is involved in writing code to use it, Listing 28-3
shows the readkey.c program (now named nreadkey.c) introduced in Listing 28-2, adapted
here to work with ncurses.
LISTING 28-3
Reading Input and Writing Output with ncurses
/*
* nreadkey.c - reads characters from stdin
*/
#include
#include
int main(int argc, char *argv[])
{
int c, i = 0;
int maxx, maxy;
int y, x;
/* start ncurses */
initscr();
/* draw a purty border */
box(stdscr, ACS_VLINE, ACS_HLINE);
mvwaddstr(stdscr, 1, 1, "INPUT: ");
refresh();
/* read characters until newline read */
noecho();
while ((c = getch()) != '\n') {
++i;
getyx(stdscr, y, x);
/* at the right margin */
if (x == 79) {
mvaddch(y + 1, 1, c);
} else {
waddch(stdscr, c);
}
continued
767
Programming Environments and Interfaces 28
LISTING 28-3 (continued)
refresh();
}
echo();
refresh();
/* print the character count */
getmaxyx(stdscr, maxy, maxx);
mvwprintw(stdscr, maxy - 2, 1, "characters read: %d\n", i);
curs_set(0);
refresh();
/* time to look at the screen */
sleep(3);
/* shutdown ncurses */
endwin();
return 0;
}
One of the first things you notice is that nreadkey.c is about twice as long as readkey.c. The
additional code addresses the need to set up the screen, position the cursor, and so forth.


Pages:
1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397