Skip to content

Latest commit

History

31 Commits

Folders and files

NameName
Last commit message
Last commit date

Repository files navigation

ncurses Programming Examples

A collection of 100 C programs written while working through Dan Gookin's Guide to Ncurses Programming. Each file is a self-contained example demonstrating a specific ncurses feature, organized by chapter.

Build

Requires GCC and the wide-character ncurses library (libncursesw-dev).

# Install on Debian/Ubuntu
sudo apt install gcc libncursesw5-dev
# Build all 100 programs into bin/
make
# Remove binaries
make clean

On Windows, compile via WSL (Ubuntu 24.04 tested).

Test

End-to-end tests drive the real compiled programs inside a headless tmux pane, send actual keystrokes, and assert on the rendered screen. They need tmux and python3 (standard library only) in addition to the build toolchain.

# Linux / WSL
tests/run.sh
# On Windows, run them under WSL
wsl -e bash tests/run.sh

See tests/README.md for how the harness works and how to add cases.

Run any example from the bin/ directory in a terminal that supports ncurses (any standard Linux terminal or WSL terminal):

bin/09-06_quad

Chapter 00 — Introduction

FileDescription
00-01_box.cDraws a border around stdscr using box(). The first ncurses program.

Chapter 01 — Hello, ncurses

FileDescription
01-01_goodbye.cPrints "Goodbye, cruel world!" — the minimal ncurses program skeleton: initscr, addstr, getch, endwin.

Chapter 02 — Input and Output

FileDescription
02-02_add1.cPrints characters one at a time with 100 ms delays using addch and napms.
02-03_add2.cConcatenates two strings and displays the result with addstr.
02-04-add3.cSame as above but uses move() to reposition the cursor before printing.
02-05_yoda.cFormatted output with printw — displays Yoda's age.
02-06_typewriter.cReads keypresses in a loop with getch; exits on ~. Demonstrates raw character input.
02-07_yourname.cCollects first and last name with getnstr, enforcing buffer limits.
02-08_sushi.cCalculates a sushi order total using scanw for integer input.

Chapter 03 — Colors and Attributes

FileDescription
03-01_twinkle.cCycles text through A_BOLD, A_BLINK, and A_NORMAL attributes.
03-02_annoy.cDisplays words with alternating A_BOLD and A_UNDERLINE.
03-03_colortest.cChecks terminal color support with has_colors() before calling start_color().
03-04_yellowred.cDefines one color pair (COLOR_YELLOW on COLOR_RED) and applies it.
03-05_colorful.cMultiple color pairs: black-on-red and bold yellow-on-black.
03-06_pink.cCreates a custom "pink" color with init_color(COLOR_RED, 1000, 750, 750).
03-07_bgcolor1.cSets the screen background color with bkgd().
03-08_bgcolor2.cApplies several background color changes in sequence.
03-09_notice.cDemonstrates beep() for an audible alert and flash() for a visual flash.

Chapter 04 — Characters and Attributes

FileDescription
04-01_charattrib.cDisplays every text attribute: STANDOUT, UNDERLINE, REVERSE, BLINK, DIM, BOLD, ALTCHARSET, INVIS, PROTECT, and the extended set.
04-02_changechar.cUses addch with attributes and move() to place styled individual characters.
04-03_attrtest.cExtended version of 04-01 — comprehensive attribute showcase.
04-04_pi.cRenders the π symbol using the ACS alternative character set (ACS_PI).
04-05_acslist.cIterates through ACS codes 0–127, printing each symbol.
04-06_acsstring.cRenders an entire string in the ACS character set using A_ALTCHARSET.
04-07_aBox.cDraws a box manually with ACS line-drawing characters (ULCORNER, HLINE, VLINE, etc.).
04-08_chtypestring.cBuilds a chtype array where each cell carries its own attribute, then displays it.
04-09_addchstr.cAdds an entire pre-attributed chtype string at once with addchstr().
04-10_boxarray.cDraws an ASCII-art box from a character array.
04-11_unicode.cDisplays the Unicode coffee-cup character ☕ (U+2615) via cchar_t and wadd_wch. Requires -lncursesw.
04-12_ustring.cPrints the Russian word "привет" (hello) as a wide-character string with addwstr.

Chapter 05 — Screen and Cursor Positioning

FileDescription
05-01_screensize.cReads terminal dimensions with getmaxy() / getmaxx() and prints them.
05-02_stdscrsize.cEquivalent using the LINES and COLS macros.
05-03_corners.cPlaces * in all four corners with 500 ms pauses using mvaddch.
05-03_ncurses.cVariant of 05-02 — prints window dimensions.
05-04_ctitle.ccenter() helper that calculates horizontal indent to center a string on screen.
05-05_whereami.cTracks and displays the cursor's current row/col with getcury() / getcurx().

Chapter 06 — Text Manipulation

FileDescription
06-01_text1.cFills the screen with alternating lines of text.
06-02_text2.cInserts a blank line above existing text with insertln().
06-03_text3.cInserts two blank lines and then writes into them.
06-04_text4.cInserts text at a specific position within existing content.
06-05_marquee1.cTypewriter effect: builds a string right-to-left using insch().
06-06_marquee2.cExtends the marquee with an alphabet header row.
06-07_text5.cUses insstr() to insert a whole string at the cursor position.
06-08_text6.cDeletes an entire line with deleteln().
06-09_text7.cDeletes individual characters with delch().
06-10_cat.cWord replacement: removes one word character-by-character then inserts another with delch/insch.
06-11_insdel.cInsert/delete multiple rows at once with insdelln().

Chapter 07 — Screen Clearing

FileDescription
07-01_cls.cClears the entire screen with clear().
07-02_clearline.cClears from the cursor to end-of-line with clrtoeol().
07-03_clearbot.cClears from the cursor to bottom-of-screen with clrtobot().

Chapter 08 — Keyboard Input

FileDescription
08-01_yourname.cName input with a confirmation loop — re-prompts until the user answers y.
08-02_keywait1.cUses nodelay() for non-blocking input; increments a counter while waiting.
08-03_keywait2.cCounts in a tight loop until the spacebar is pressed (non-blocking mode).
08-04_secretkey.cReads two keypresses and checks they match; the second is read with noecho().
08-05_kbhit.cImplements a kbhit() function (DOS-style) using nodelay and ungetch.
08-06_arrowkeys.cEnables keypad(stdscr, TRUE) to receive KEY_UP/DOWN/LEFT/RIGHT.
08-07_greetings.cGets first and last name with getnstr.
08-08_urpwd.cUsername/password form: password field uses noecho() to hide input.
08-09_flush.cDemonstrates flushinp() — discards pending input accumulated during a delay.

Chapter 09 — Windows

FileDescription
09-01_anotherwin.cCreates a second full-screen window with newwin(0, 0, 0, 0).
09-02_switch.cTwo windows with different background colors (blue stdscr, red overlay).
09-03_switchback.cUses touchwin() to force a full redraw when switching focus between windows.
09-04_touch.cSmall centered window; touchwin() marks it dirty to trigger a refresh.
09-05_halfpint.cCreates a half-size window positioned at the screen center.
09-06_quad.cDivides the screen into four quadrant windows, each with a distinct color.
09-07_twowin.cTwo full-height side-by-side windows; demonstrates delwin() to release one.
09-08_border.cDraws a border on stdscr with border() using default line-drawing chars.
09-09_aborder.cCustom border using comma characters for all eight border positions.
09-10_box.cDraws the standard box border with box(stdscr, 0, 0).
09-11_quadborders.cFour quadrant windows, each with its own box() border.

Chapter 10 — Subwindows

FileDescription
10-01_sub1.cCreates a subwindow inside a bordered stdscr with subwin().
10-02_sub2.cCentered subwindow inside a main window.
10-03_sub3.cUses derwin() (derived window) where coordinates are relative to the parent.
10-04_subsub.cNested derived windows three levels deep: grandpa → father → son.
10-05_delsub.cCreates and then removes a subwindow with delwin().

Chapter 11 — Window Copying

FileDescription
11-01_overwrite1.cCopies content from a red window onto a blue one with overwrite().
11-02_overwrite2.cSame as above, but calls touchwin() so the destination redraws correctly.
11-03_overlay.coverlay() — copies only non-blank characters, leaving the background visible.
11-04_copywin.cCopies a rectangular region transparently with copywin(..., TRUE).
11-05_copywin2.cSame rectangle copy non-transparently with copywin(..., FALSE).
11-06_dup.cdupwin() — creates an independent copy of a window.
11-07_movewin.cMoves a window to a new screen position with mvwin().

Chapter 12 — Scrolling

FileDescription
12-01_scrolling1.cShows that text naturally wraps but does not scroll by default.
12-02_scrolling2.cEnables auto-scroll with scrollok(stdscr, TRUE).
12-03_scrollsub.cEnables scrolling within a subwindow.
12-04_scroll.cManually scrolls the window one line with scroll().
12-05_scrup3.cScrolls three lines at once with scrl(3).
12-06_scrollreg.cRestricts scrolling to a middle band using setscrreg().

Chapter 13 — Pads

FileDescription
13-01_newpad1.cCreates a pad (virtual window larger than the screen) with newpad().
13-02_newpad2.cFills a pad with data and displays a viewport into it with prefresh().
13-03_sonofapad.cCreates a sub-pad inside a pad with subpad().

Chapter 14 — Mouse

FileDescription
14-01_mousetest.cChecks mouse support via NCURSES_MOUSE_VERSION and mousemask().
14-02_mspy.cReports real-time mouse coordinates (row, col) as the cursor moves.
14-03_clickput.cPlaces a * wherever the user clicks using BUTTON1_CLICKED.
14-04_blick.cDetects and labels button states: PRESSED, RELEASED, CLICKED, DOUBLE_CLICKED for buttons 1–3.

Chapter 15 — Miscellaneous

FileDescription
15-01_curset.cCycles the cursor through invisible, normal, and very visible with curs_set(0/1/2).
15-02_steps.cDraws diagonal and horizontal lines using hline() and vline().
15-03_plus.cDraws a centered crosshair using hline/vline with ACS line characters.
15-04_dumpwin.cSaves the current screen to a file with scr_dump("dump.win").
15-05_undump.cRestores a previously saved screen from file with scr_restore("dump.win").

ncurses API Quick Reference

FunctionPurpose
initscr() / endwin()Initialize and tear down ncurses
addch() / addstr() / printw()Output a character, string, or formatted text
mvaddch() / mvaddstr()Move cursor then output
getch() / getnstr() / scanw()Read a key, bounded string, or formatted input
attron() / attroff() / attrset()Enable/disable/replace text attributes
start_color() / init_pair() / COLOR_PAIR()Set up and apply color pairs
init_color()Define a custom color (requires terminal support)
bkgd()Set window background character and attributes
newwin() / delwin()Create and destroy a window
subwin() / derwin()Create a subwindow (absolute or parent-relative coords)
refresh() / wrefresh() / touchwin()Push virtual screen to terminal
move() / wmove()Position the cursor
clear() / clrtoeol() / clrtobot()Erase screen regions
insertln() / deleteln() / insch() / delch()Insert/delete lines and characters
scrollok() / scroll() / scrl() / setscrreg()Control scrolling
newpad() / prefresh() / subpad()Pads — virtual windows larger than the screen
mousemask() / getmouse()Enable and read mouse events
keypad() / nodelay() / noecho()Input mode flags
beep() / flash()Audible and visual alerts
curs_set()Control cursor visibility
hline() / vline()Draw horizontal/vertical lines
scr_dump() / scr_restore()Save and restore screen state
box() / border()Draw a border around a window
overwrite() / overlay() / copywin() / dupwin()Copy window content
napms()Sleep for N milliseconds

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

1 watching

Forks

Releases

Packages

Used by

Contributors

Languages