conio.h
conio.h is a non-standard C header file originally developed by Borland for their Turbo C compiler, introduced in 1987, targeting MS-DOS environments, providing functions for direct console input and output operations.[1] It enables low-level manipulation of the text-based console, including unbuffered keyboard input, screen clearing, cursor positioning, and text attribute control, which were essential for creating interactive applications in the absence of graphical interfaces.[1] The header's functions bypass standard I/O buffering to allow real-time responses, making it particularly valuable for DOS-era programming tasks such as game development, menu systems, and password entry.[1] Borland's implementation, detailed in their 1992 library reference, includes core routines for reading characters (getch(), getche()), checking key presses (kbhit()), outputting text (cputs(), cprintf()), and managing display elements (clrscr(), gotoxy(), textcolor()).[1]
Microsoft provides similar functionality in their C runtime library (CRT) for Windows and DOS compatibility, including functions prefixed with underscores (e.g., _getch(), _kbhit(), _putch()) to support unbuffered console I/O in console applications.[2][3][4] Although conio.h is not part of the ISO C standard and has been largely superseded by platform-specific APIs like POSIX termios or Windows Console API in modern systems, it persists in some compilers (e.g., DJGPP, with partial support in MinGW) for legacy and educational purposes.[5]
Overview
Purpose and Scope
conio.h is a non-standard header file in the C and C++ programming languages, providing a collection of functions for console input and output operations primarily targeted at text-mode environments. It was first developed for MS-DOS compilers, notably popularized by Borland compilers, offering developers tools to interact directly with the console hardware.[6] The core scope of conio.h encompasses low-level access to console features, such as unbuffered keyboard input, screen clearing, cursor positioning, and attribute control for text display, which enable real-time manipulation of text-based user interfaces. These capabilities are not part of the standard C library's stdio.h, which focuses on buffered, file-like stream I/O for portability across platforms. In contrast, conio.h emphasizes direct, non-portable control over console hardware, supporting operations like reading keys without echo or altering screen colors and positions immediately.[6][2] Key use cases for conio.h include DOS-era applications, game development where immediate keyboard response is essential, and simple text-based user interfaces requiring direct screen manipulation, such as clearing the display or moving the cursor without standard library overhead. For instance, it facilitates unbuffered input via functions like getch() and screen resets with clrscr(), supporting efficient text-mode programming in legacy environments.[6][7]Historical Development
The header was originally developed by Lattice Inc. for their Lattice C compiler, released in 1982 as the first C compiler for the IBM PC, where its functions mapped to early DOS interrupts.[8] conio.h was popularized in 1987 by Borland International as part of their Turbo C compiler suite for MS-DOS, specifically designed to facilitate efficient console input and output programming on IBM PC-compatible systems.[9] The header provided low-level access to video memory and BIOS interrupts, enabling developers to perform direct screen manipulations without relying on the slower DOS API, which simplified the creation of interactive text-based applications.[9] In the 1990s, the library evolved alongside Borland's progression to Borland C++ and Turbo C++, with enhancements that supported advanced console features such as color attributes, cursor positioning, and interrupt-based keyboard handling, broadening its applicability for more sophisticated text-mode interfaces.[10] Microsoft included conio.h functionality in their C runtime library starting with version 4.0 in 1986, which was later carried over to Visual C++ compilers in the 1990s.[11][2] Additionally, open-source efforts like DJGPP, a port of the GNU Compiler Collection to DOS released in the early 1990s, revived and extended conio.h functionality for 32-bit protected mode environments, maintaining its relevance for legacy DOS development. The header reached its zenith of usage during the MS-DOS era of the 1980s and 1990s, powering a wide array of educational software, shareware utilities, and rudimentary games that leveraged its straightforward API for real-time console interactions.[12] However, post-2000, conio.h experienced a marked decline as the computing landscape shifted toward graphical user interfaces in Windows and adherence to POSIX standards in Unix-like systems; its platform-specific nature rendered it incompatible with ISO C, which does not include or endorse such extensions.[13]Functions
Input Functions
The input functions in conio.h provide mechanisms for reading keyboard input in a non-buffered, direct manner, which is particularly useful for interactive console applications requiring immediate response without waiting for enter key presses.[2] These functions originated in MS-DOS environments and are designed to bypass standard input buffering, allowing developers to capture keystrokes as they occur.[14] Thegetch() function reads a single character from the console without echoing it to the screen or requiring a newline, returning an integer value representing the character.[2] For ordinary keys, it returns the ASCII code; however, for extended keys such as arrow keys or function keys, the first call to getch() returns 0 (or 0xE0 for certain keys), and a subsequent call returns the specific scan code of the key.[2] This two-byte sequence enables detection of non-printable keys in applications like text editors or games.[2]
In contrast, getche() operates similarly to getch() but echoes the read character to the console immediately upon input.[14] It also handles extended keys via the same two-call mechanism, returning 0 or 0xE0 first, followed by the scan code.[14] This echoing behavior makes getche() suitable for scenarios where visual feedback is desired without full line buffering, such as password entry with visible characters or simple prompts.[14]
The kbhit() function checks whether a key has been pressed without blocking or consuming the input, returning a non-zero value if a keystroke is available in the input buffer and zero otherwise.[3] It is commonly paired with getch() or getche() in polling loops to enable non-blocking input handling, preventing programs from halting execution while waiting for user interaction.[3] For instance, in game development, a loop might use if (kbhit()) { int ch = getch(); /* process key */ } to respond to player inputs during rendering cycles without interrupting the main program flow.[3] Handling special keys involves checking for the initial 0 return from getch() and reading the follow-up scan code to identify actions like movement (e.g., arrow keys returning codes 72h for up, 80h for down).[2]
Additional input functions include ungetch(int ch), which pushes the character ch back into the input buffer so that a subsequent getch() or getche() will return it, with prototype int ungetch(int ch); and returning the pushed character on success.[15] The getpass(const char *prompt) function prompts for a password without echoing input, returning a pointer to a static string containing the entered password (limited to 8 characters), prototyped as char *getpass(const char *prompt);.[15] For buffered string input, cgets(char *str) reads a line into str, stopping at a specified width and handling the terminating newline, with prototype char *cgets(char *str); and returning a pointer to the string on success.[15]
Internally, these functions in the original MS-DOS implementation rely on BIOS interrupt 16h (INT 16h) for low-level keyboard services, where subfunction AH=00h waits for and retrieves a keystroke from the type-ahead buffer, returning the ASCII code in AL and scan code in AH.[16] Subfunction AH=01h is used by kbhit() equivalents to test for key availability without removal, and AH=10h supports enhanced keyboards for extended key handling.[17] This BIOS-level access ensures direct hardware interaction, though modern implementations in Windows translate these to console API calls for compatibility.[3]
Output and Screen Functions
The output and screen functions in conio.h provide low-level mechanisms for rendering text directly to the console display, enabling efficient screen manipulation without relying on buffered I/O or standard library formatting routines like printf. These functions are particularly suited for text-mode environments on IBM PC compatibles, where they facilitate real-time updates for applications such as games or interactive tools. When the global variable directvideo is set to 1, many of these operations perform direct writes to video memory for speed, bypassing BIOS interrupts.[15] The putch function outputs a single character to the console at the current cursor position within the defined text window. Its prototype isint putch(int c);, where c is the ASCII character to display. It returns the character written upon success or EOF (-1) if an error occurs, such as an invalid output position. Unlike standard output functions, putch does not interpret newline characters (\n) as carriage return-linefeed pairs and advances the cursor accordingly after writing. In direct video mode, it writes the character and its associated attribute byte directly to screen memory.[15][15]
The cputs(const char *str) function outputs a string to the console without a trailing newline, advancing the cursor after the last character, with prototype int cputs(const char *str); and returning the last character printed or EOF on error.[15] Similarly, cprintf(const char *format, ...) performs formatted output directly to the console, similar to printf but bypassing standard I/O buffering, with prototype int cprintf(const char *format, ...); and returning the number of characters output.[15]
The clrscr function clears the entire screen by filling it with spaces using the current text background color and repositions the cursor to the home position (1,1). Its prototype is void clrscr(void);, with no return value. This operation affects the full screen or the current text window if one is defined, resetting video memory to a blank state for fresh output. Cursor positioning is restored to the upper-left corner after clearing, ensuring alignment for subsequent writes.[15][15]
The clreol function erases the portion of the current line from the cursor position to the end of the line, filling it with spaces based on the current background color, while leaving the cursor in place. Its prototype is void clreol(void);, and it returns nothing. This allows partial line refreshes without disrupting the entire screen or moving the cursor, making it useful for overwriting trailing text. In text mode, it modifies video memory only for the affected segment of the line within the current window boundaries.[15][15]
The delline and insline functions manage line-level screen scrolling by deleting or inserting lines at the current cursor row. The delline function, with prototype void delline(void);, removes the line containing the cursor and shifts all subsequent lines upward, causing the bottom line to scroll off-screen; it has no return value and operates within the current text window on IBM PC-compatible hardware. Conversely, insline, prototyped as void insline(void);, inserts a blank line (filled with spaces using the current background color) at the cursor row, pushing existing lines below it downward and scrolling the bottom line off-screen. Both functions alter video memory by shifting content vertically, enabling smooth scrolling effects without full screen redraws.[15][15]
The window function defines a rectangular region of the screen as the active text window, restricting subsequent output operations to that area for localized display management. Its prototype is void window(int left, int top, [int](/page/INT) right, [int](/page/INT) bottom);, where coordinates are 1-based absolute screen positions (e.g., left=1, top=1, right=80, bottom=25 for a full 80x25 screen in standard text mode); it returns nothing. The minimum window size is 1x1, and output beyond the bounds is clipped, with the cursor wrapping within the window rather than the full screen. By default, the window encompasses the entire display, and changes affect video memory access for all compatible output functions. In color text mode, these operations target segment 0xB800 for direct memory writes when enabled.[15][15][18]
Attribute and Cursor Functions
The attribute and cursor functions in conio.h provide mechanisms for modifying the visual appearance of text output and controlling the position of the text cursor on the console screen, primarily in text-mode environments such as DOS. These functions enable developers to set foreground and background colors, adjust text intensity, retrieve current display information, and manipulate cursor coordinates, facilitating the creation of formatted console interfaces without direct hardware access.[19] Color control is achieved through functions that set the foreground and background attributes for subsequent text output. Thetextcolor(int color) function sets the foreground color of text, accepting an integer value or symbolic constant from 0 to 15, where the change applies to all text printed afterward until modified.[19] Similarly, textbackground(int color) establishes the background color for text output, using the same range of values, and affects the fill color behind characters.[19] These functions operate on the standard 16-color palette defined in conio.h (often shared with graphics.h), allowing for combinations that produce up to 256 possible attribute values when foreground and background are paired.[19] The textattr(int newattr) function sets both foreground and background attributes in a single call, using a combined integer where the low 4 bits are foreground and high 4 bits background, prototyped as void textattr(int newattr);.[15]
The color constants are enumerated as follows, representing the VGA-compatible palette used in text modes:
| Constant | Value | Description |
|---|---|---|
| BLACK | 0 | Black |
| BLUE | 1 | Blue |
| GREEN | 2 | Green |
| CYAN | 3 | Cyan |
| RED | 4 | Red |
| MAGENTA | 5 | Magenta |
| BROWN | 6 | Brown |
| LIGHTGRAY | 7 | Light Gray |
| DARKGRAY | 8 | Dark Gray |
| LIGHTBLUE | 9 | Light Blue |
| LIGHTGREEN | 10 | Light Green |
| LIGHTCYAN | 11 | Light Cyan |
| LIGHTRED | 12 | Light Red |
| LIGHTMAGENTA | 13 | Light Magenta |
| YELLOW | 14 | Yellow |
| WHITE | 15 | White |
highvideo() and lowvideo(), which adjust the foreground color's brightness by setting or clearing the high-intensity bit (adding or subtracting 8 from the color value, respectively).[19] For instance, calling highvideo() on a base color like GREEN (2) effectively sets it to LIGHTGREEN (10), enhancing visibility in console applications.[19] These functions do not alter the background and are useful for emphasizing sections of output without changing the base color palette. The normvideo() function restores normal video attributes, resetting to default colors and intensity, with prototype void normvideo(void);.[15]
Cursor positioning functions allow precise control over where text appears on the screen, using 1-based indexing for columns (x) and rows (y). The gotoxy(int x, int y) function relocates the cursor to the specified coordinates within the current text window, with x typically ranging from 1 to 80 and y from 1 to 25 (or up to 43 or 50 in extended modes).[19] Complementary query functions, wherex() and wherey(), return the current column and row positions as integers, enabling programs to track and restore cursor locations dynamically.[19]
The textmode(int newmode) function sets the console to a specific text mode, such as C80 for color 80-column or BW40 for black-and-white 40-column, with prototype void textmode(int newmode); and predefined constants in conio.h.[15]
To retrieve comprehensive display state, gettextinfo(struct text_info *info) populates a text_info structure with details including the current screen mode, cursor position (via curx and cury fields), attribute settings, and window boundaries (e.g., screenheight, screenwidth).[19] This function is essential for adaptive console programs that need to query the environment before applying attributes or moving the cursor, ensuring compatibility across different text modes.[19] All these functions assume a text-based console and may behave differently or require emulation in modern non-DOS systems.[19]