Using C/C++, how do you print to stdout in color, but only if the terminal supports it? Using C/C++, how do you print to stdout in color, but only if the terminal supports it? c c

Using C/C++, how do you print to stdout in color, but only if the terminal supports it?


Probably the easiest way to check is simply:

isatty(fileno(STDOUT))

This will return 1 if your standard output is being sent to any sort of terminal. In practice, any terminal will either support or ignore VT100 color codes; examining terminfo is unnecessary unless you expect to be outputting to certain really unusual hardware terminals. (Most of which haven't been made in decades.)

To output colors, use the (extended) SGR sequence:

"\x1b[%dm"

where %d is one of the following values for commonly supported colors:

0: reset colors/style1: bold4: underline30 - 37: black, red, green, yellow, blue, magenta, cyan, and white text40 - 47: black, red, green, yellow, blue, magenta, cyan, and white background

There are more values, but these are the most widely supported ones. Again, examining terminfo is largely unnecessary for these control codes, as every software terminal worth its salt will support (or ignore) them.

If you need to change multiple attributes at once, you can specify them all at once, separated by semicolons. For instance, the following sequence will sear your eyeballs with bold magenta text on a green background:

"\x1b[1;35;42m"