I have a C file running on Linux. It prints some lines in red (failures) and some in green (passes). As you might expect, it uses escape codes in the printf statements as follows:
#define BLACK "\033[22;30m"
#define GREEN "\033[22;31m"
printf(GREEN "this will show up green" BLACK "\n");
If the BLACK at the end wasn't there, the terminal text will continue to be green for everything. In case you didn't catch it, that's fine for a terminal window with a non-black background, but otherwise you'll end up with black-on-black. Not good! Running the program has this problem, as does capturing the output in a text file and then viewing the file with "more" or "less".
Is there a code to restore defaults instead of specifying a color at the end of the printf statement? This needs to be in C, but I would be interested in reading about other approaches.
I updated my macros as follows (note 31 is for red):
#define RESET_COLOR "\e[m"
#define MAKE_GREEN "\e[32m"
printf(MAKE_GREEN "this will show up green" RESET_COLOR "\n");
I found the following links helpful in understanding how these codes work:
http://www.phwinfo.com/forum/comp-unix-shell/450861-bash-shell-escapes-not-working-via-putty-ssh.html explains what these escape sequences do, and to use ncurses if portability is needed.
http://www.linuxselfhelp.com/howtos/Bash-Prompt/Bash-Prompt-HOWTO-6.html
ANSI codes shows even more escape sequences; It is useful to get the big picture
Changing the color of text or shapes in your C program can help them pop when the user runs your program. Changing the color of your text and objects is a fairly straightforward process, and the necessary functions are included in the standard libraries. You can change the color of anything you output on the screen.
Try using:
#define RESETCOLOR "\033[0m"
That should reset it to the defaults.
More about these terminal codes can be found in ANSI escape code.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With