How can I print to the console in color in a cross-platform manner?

colors, console, linux, macos

Solution

You can use the ANSI colour codes. Here's an example program:

#include <stdio.h>
    
int main(int argc, char *argv[])
{
  printf("%c[1;31mHello, world!\n", 27); // red
  printf("%c[1;32mHello, world!\n", 27); // green
  printf("%c[1;33mHello, world!\n", 27); // yellow
  printf("%c[1;34mHello, world!\n", 27); // blue
  return 0;
}

The `27` is the `escape` character. You can use `\e` if you prefer.

There are lists of all the codes all over the web. Here is one.

Problem

How can I output colored text using "printf" on both Mac OS X and Linux?

Original source