colorful text using printf in C colorful text using printf in C c c

colorful text using printf in C


I know that this is incredibly easy to do in C++, but I found this for you to look at in C:

#include <stdio.h>#include <windows.h>   // WinApi headerint main(){  HANDLE  hConsole;    int k;  hConsole = GetStdHandle(STD_OUTPUT_HANDLE);  // you can loop k higher to see more color choices  for(k = 1; k < 255; k++)  {    SetConsoleTextAttribute(hConsole, k);    printf("%3d  %s\n", k, "I want to be nice today!");  }  getchar();  // wait  return 0;}

All of the comments will help you to find your way through the code - hope it helps!


If you want to print colored text in Windows console, you will have to use Windows API. ANSI.sys support is no longer present in Windows.

In Linux you can still use ANSI escape sequences to color text.


If you are constrained to using just printf(), this requires knowledge of the terminal to which you're writing. The chances are it is an ANSI-style terminal, so it can be done. The Unix curses (Linux ncurses) library handles such information in a terminal-independent way. Basically, you will need to define or manufacture control strings to turn the terminal into red mode and then reset it back again (but how do you know what state it was in before you changed it to writing red text?). The libraries mentioned keep track of the state information, amongst many other details.

However, if you get the strings organized, then code like this will do the trick (more or less):

static const char to_red[] = "\033...";static const char to_black[] = "\033...";printf("%s%s%s\n", to_red, "hello world", to_black);

The hard part is determining what goes in the constant strings (which need not actually be constant).

All this means there is probably a Windows-specific interface that can be used to do the job, but that does not really involve printf() for controlling the colours; you call the Windows API to set the colour, then write with printf(), then call the API again to reinstate the colour. There is probably a query function to allow you to find the current setting, which you use before changing it.