Welcome to the world of curses. Before we plunge into the library and look into its various features, bells and whistles, let's write a simple program and say hello to the world.
To use ncurses library functions, you have to include ncurses.h and to link the program with ncurses library the flag -lncurses should be added. ncurses.h already includes stdio.h.
#include <ncurses.h> . . . compile and link: gcc <program file> -lncurses |
The above program prints "Hello World !!!" to the screen and exits. This program shows how to initialize curses and do screen manipulation and end curses mode. Let's dissect it line by line.
The function initscr() initializes the terminal in curses mode. In some implementations it clears the screen and presents a blank screen. To do any screen manipulation using curses package this has to be called first. This function initializes the curses system and allocates memory for our present window which is called 'stdscr' and some other datastructures. Under extreme cases this function might fail due to insufficient memory to allocate memory for curses library's data structures.
After this is done we can do a variety of initializations to customize our curses settings. These details will be explained later.
The next line printw prints the string "Hello World !!!" on to the screen. This function is analogous to normal printf in all respects except that it prints the data in a window called stdscr at the current (y,x) co-ordinates. Since our present co-ordinates are at 0,0 the string is printed at the left hand corner of the window.
This brings us to that mysterious refresh(). Well, when we did printw actually the data is written to an imaginary window called stdscr, which is not updated on the screen yet. The job of printw is to update a few flags and data structures and write the data to a buffer corresponding to stdscr. In order to bring it to the screen we need to call refresh() and tell the curses system to dump the contents on the screen.
The philosophy behind all this is to allow the programmer to do multiple updates on the imaginary screen or windows and do a refresh once all his screen update is done. refresh() checks the window and updates only the portion which has been changed. This gives good response and offers greater flexibility too. But it is sometimes frustrating to beginners. A common mistake committed by beginners is to forget to call refresh() after they did some update through printw() class of functions. I still forget to add it some times :-)
And finally don't forget to end the curses mode. Otherwise your terminal might behave strangely after the program quits. endwin() frees the memory taken by curses sub-system and it's data structures and puts the terminal in normal mode. This function must be called after you are done with the curses mode.