Change Text Color in the Console

Viewed 107

I'm new to C and I was wondering if using system() is a good way to change the color of a text in the console.

int main()
{
    system("echo \x1b[32m");
    printf("hello");

    return 0;
}

And is it cross-platform ?

2 Answers

You can just do

printf("\x1b[32m");

as with the system command you are just telling it to print that escape code which turns the console green, so you can just print it by itself to have the same effect. Printf works on most devices where as system does not work on some, so printf is preferred.

Here is a list of more color codes if you are interested: https://gist.github.com/RabaDabaDoba/145049536f815903c79944599c6f952a

There are two problems with this code:

  1. system("echo \x1b[32m"); does the exact same thing as puts("\x1b[32m"); but more slowly. It creates a subprocess and runs a command interpreter of some stripe, which must then interpret the command echo ␛[32m. I don't know any reason to write system("echo ...").

  2. The byte sequence ␛[32m (1b 5b 33 32 6d) is an ANSI X3.64 terminal control code which may or may not be understood by whatever stdout is connected to. It is better to use a terminal control library, such as ncurses, which will figure out what it's talking to and use the correct control sequence (or not use colors at all, if they're not supported).

Related