/* Read http://z0b.kapsi.fi/snippets.php before using this code. Thank you. */ /* Background colors, underline, bold and reverse video styles also would be nice additions. I might add them later. Keep in mind that the "bright" colors (8-15) can actually be bold. This depends on the terminal you're using. Unlike the Windows version, this supports Unicode out-of-the- box via UTF-8. */ #include #include #include static void cprintf(const char *fmt, ...) { static const char *colors[] = { "\e[0;30m", "\e[0;34m", "\e[0;32m", "\e[0;36m", "\e[0;31m", "\e[0;35m", "\e[0;33m", "\e[0;37m", "\e[1;30m", "\e[1;34m", "\e[1;32m", "\e[1;36m", "\e[1;31m", "\e[1;35m", "\e[1;33m", "\e[1;37m" }; if (!fmt) return; // format static char buf[2048]; va_list ap; va_start(ap, fmt); vsnprintf(buf, 2046, fmt, ap); buf[2047] = '\0'; va_end(ap); // and print const char *c; char *p = buf; while (*p) { // find the next color change char *s = strchr(p, '#'); if (s) { // color changes, terminate current block and show it *s = '\0'; for (c = p; *c; ) putchar(*c++); // then change the color (or print a hash sign) if (*(s + 1)) { const char c = *++s; if (c >= '0' && c <= '9') printf(colors[c - '0']); else if (c >= 'A' && c <= 'F') printf(colors[c - 'A' + 10]); else if (c >= 'a' && c <= 'f') printf(colors[c - 'a' + 10]); else if (c == 'R') printf("\e[0m"); else if (c == '#') putchar('#'); } // jump over this block and the color change p = s + 1; } else { // no more color changes, print the // rest of the string and stop for (c = p; *c; ) putchar(*c++); break; } } } int main() { cprintf("#CHe#Ell#Ao w#9or#Dld#F!#R\n"); return 0; }