Who knew about printf() in C being able to specify foreground/background colors?
ProgrammingThis forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.
Notices
Welcome to LinuxQuestions.org, a friendly and active Linux Community.
You are currently viewing LQ as a guest. By joining our community you will have the ability to post topics, receive our newsletter, use the advanced search, subscribe to threads and access many other special features. Registration is quick, simple and absolutely free. Join our community today!
Note that registered members see fewer ads, and ContentLink is completely disabled once you log in.
If you have any problems with the registration process or your account login, please contact us. If you need to reset your password, click here.
Having a problem logging in? Please visit this page to clear all LQ-related cookies.
Get a virtual cloud desktop with the Linux distro that you want in less than five minutes with Shells! With over 10 pre-installed distros to choose from, the worry-free installation life is here! Whether you are a digital nomad or just looking for flexibility, Shells can put your Linux machine on the device that you want to use.
Exclusive for LQ members, get up to 45% off per month. Click here for more info.
Who knew about printf() in C being able to specify foreground/background colors?
I got curious during the construction of my program to search for blocks of text that contain certain words, and wanted to print out blocks of text with the words I was searching for, initially, in ALL CAPS and seperated by tabs for easy identification. That got boring, though, so I thought, "Can printf do colors, too?"
Yes it can.... Who knew?
Code:
/*Text attributes
0 All attributes off
1 Bold on
4 Underscore (on monochrome display adapter only)
5 Blink on
7 Reverse video on
8 Concealed on
Foreground colors
30 Black
31 Red
32 Green
33 Yellow
34 Blue
35 Magenta
36 Cyan
37 White
Background colors
40 Black
41 Red
42 Green
43 Yellow
44 Blue
45 Magenta
46 Cyan
47 White
*/
Well, I don't think that's printf() doing the color changing. Those are escape sequences interpreted by the terminal. So, what happens with that string of characters depends on what features the terminal supports.
A: Because it's EQUALLY likely to NOT work in any random xterm window or command prompt you might try. There are arguably much better ways to accomplish the same thing.
I believe that ncurses interprets the TERM variable, and references the terminfo definition from the termcap library. Since I don't use ncurses, I could be completely wrong on this, however.
LinuxQuestions.org is looking for people interested in writing
Editorials, Articles, Reviews, and more. If you'd like to contribute
content, let us know.