2

I would like to use printf with colors:

something like:

#include <stdio.h>

#define KNRM  "\x1B[0m"
#define KRED  "\x1B[31m"
#define KGRN  "\x1B[32m"
#define KYEL  "\x1B[33m"
#define KBLU  "\x1B[34m"
#define KMAG  "\x1B[35m"
#define KCYN  "\x1B[36m"
#define KWHT  "\x1B[37m"

int main()
{
    printf("%sred\n", KRED);
    printf("%sgreen\n", KGRN);
    printf("%syellow\n", KYEL);
    printf("%sblue\n", KBLU);
    printf("%smagenta\n", KMAG);
    printf("%scyan\n", KCYN);
    printf("%swhite\n", KWHT);
    printf("%snormal\n", KNRM);

    return 0;
}
  • Can I assume it will be compiled with GCC and will be supported in any unix like platform?
  • If not, How can I print in colors to stdout ?
Community
  • 1
  • 1
0x90
  • 39,472
  • 36
  • 165
  • 245
  • Not only that, but you missed the important call `SetConsoleTextAttribute(hConsole, k);`, which actually switches the colors. – Xymostech Apr 11 '13 at 19:25
  • @FredLarson wrong link thanks for noting me. I fixed. – 0x90 Apr 11 '13 at 19:31
  • 1
    You can assume that it will send those control characters to stdout. You can't assume that doing so will have any effect on the color of the displayed text. For example, I usually use `xterm` with colors disabled. – Keith Thompson Apr 11 '13 at 20:08

2 Answers2

4

It is not a function of the platform, it is a function of the terminal.

If you attach a VT525 to the serial port of your computer, you will see all of the glorious ANSI colors. If you attach a VT100, you will see mostly green on black. If you attach an IBM 2741, you will see mostly black on white, or perhaps brown or blue or green or red if you have these colors of tape, but not at the same time (you would need to swap tapes by hand).

Many, but not all, terminal emulators running on various windowing systems these days support ANSI color selection sequences.

On a Unix-like system the recommended way to discover and use terminal capabilities (color and many many other features) is by using a library such as ncurses. The library will select the right escape sequences for your terminal or terminal emulator, and fall back to monochrome printing if color is not supported.

n. m. could be an AI
  • 112,515
  • 14
  • 128
  • 243
1

No, you really cannot assume that. Not only is it not true for all platforms, depending on terminal settings it might not even be true for all users on ANY platform.

metalhead
  • 558
  • 1
  • 10
  • 24