This item was added on: 2003/03/22
This is a highly system dependent question. Using DOS, or a compiler with the textcolor function, you can use something like this:
#include <stdio.h>
#include <conio.h>
int main ( void )
{
textcolor ( MAGENTA );
cprintf ( "This is a test\n" );
return 0;
}
The different color codes are
0 BLACK
1 BLUE
2 GREEN
3 CYAN
4 RED
5 MAGENTA
6 BROWN
7 LIGHTGRAY
8 DARKGRAY
9 LIGHTBLUE
10 LIGHTGREEN
11 LIGHTCYAN
12 LIGHTRED
13 LIGHTMAGENTA
14 YELLOW
15 WHITE
On Windows systems a Win32 API approach should be preferred:
#include <stdio.h>
#include <windows.h>
int main ( void )
{
HANDLE h = GetStdHandle ( STD_OUTPUT_HANDLE );
WORD wOldColorAttrs;
CONSOLE_SCREEN_BUFFER_INFO csbiInfo;
GetConsoleScreenBufferInfo(h, &csbiInfo);
wOldColorAttrs = csbiInfo.wAttributes;
SetConsoleTextAttribute ( h, FOREGROUND_RED | FOREGROUND_INTENSITY );
printf ( "This is a test\n" );
SetConsoleTextAttribute ( h, wOldColorAttrs);
return 0;
}
The color constants are
FOREGROUND_BLUE
FOREGROUND_GREEN
FOREGROUND_RED
FOREGROUND_INTENSITY
On systems that support curses, that approach can be used as well:
#include <curses.h>
int main ( void )
{
initscr();
if ( start_color() == OK ) {
init_pair ( 1, COLOR_RED, COLOR_BLACK );
attron ( COLOR_PAIR ( 1 ) );
addstr ( "This is a test" );
getch();
}
endwin();
return 0;
}
The color constants for curses are
COLOR_BLACK
COLOR_RED
COLOR_GREEN
COLOR_YELLOW
COLOR_BLUE
COLOR_MAGENTA
COLOR_CYAN
COLOR_WHITE
Credit: Prelude