prev up next   top/contents search

comp.lang.c FAQ list · Question 19.4

Q: How can I clear the screen?
How can I print text in color?
How can I move the cursor to a specific x, y position?

A: Such things depend on the terminal type (or display) you're using. You will have to use a library such as termcap, terminfo, or curses, or some system-specific routines, to perform these operations.

Functions in the curses library to look for are clear, move, standout/standend, and attron/attroff/attrset; the last three work with attribute codes such as A_REVERSE. In MS-DOS libraries, there are typically functions named gotoxy and clrscr or _clearscreen; you can also use the ANSI.SYS driver or low-level interrupts. Under termcap or terminfo, use tgetstr to retrieve strings like cl, so/se, and cm for clear screen, standout mode, and cursor motion respectively, then output the strings; using cm additionally requires calling tgoto. Some baroque terminals require attention to other ``capabilities'' as well; study the documentation carefully. Be aware that some older terminals may not support the desired capabilities at all.

Most modern terminal emulation schemes support the ANSI escape sequences for cursor motion and visual attributes, so if you're willing to sacrifice portability, you can print those sequences directly. Here is a tiny example to whet your appetite:

printf("\033[2J");		/* clear screen */
printf("\033[%d;%dH", 10, 20);	/* move cursor (row 10, col 20) */
printf("Hello, ");
printf("\033[7mworld\033[0m!");	/* inverse video */
Here is a link to some more explanation, and brief lists of codes. The portable way of emitting these sequences (if you're not going whole-hog and using curses) is to use termcap or terminfo; here is an example.

For clearing the screen, a halfway portable solution is to print a form-feed character ('\f'), which will cause some displays to clear. Even more portable (albeit even more gunky) might be to print enough newlines to scroll everything away (although of course this leaves the cursor at the bottom of the screen, not the top). As a last resort, you could use system (see question 19.27) to invoke an operating system clear-screen command.

References: PCS Sec. 5.1.4 pp. 54-60, Sec. 5.1.5 pp. 60-62
Strang, Programming with curses
Strang, Mui, and O'Reilly, termcap & terminfo

prev up next   contents search
about this FAQ list   about eskimo   search   feedback   copyright

Hosted by Eskimo North