Colorful output in C
Without Graphics Library
What if you realized there is a way to colorize the C program output, shown on the terminal. That too, without using or including graphics library. Yes we are talking about ‘ANSI’ escape codes. Hey, but wait a minute. We all know about ‘ASCII’, but what does ANSI escape sequence mean?🤔
ANSI escape sequences are a standard for in-band signaling to control cursor location, color, font styling and other options on video text terminals and terminal emulators. Basically with the help of ANSI escape sequences, we can print colorful text on terminal.
So let me just write a function to apply ANSI escape sequence for red text.
void red()
{
printf("\033[1;31m");
}
A function to apply ANSI sequence, for green text might look like this:
void green()
{
printf("\033[1;32m");
}
Note that, you can name your function anything you want to, but we used such names to avoid confusion.
You can simply call these functions in your code whenever you want red or green text as output in your terminal. Or alternatively, you can directly use, printf(“\033[1;31m”); for red and printf(“\033[1;32m”); for green text, before some print statement directly, without needing to define a function. But functions help us organize the code.