用C语言在终端打印彩色字符串

转载:https://blog.csdn.net/lwfcgz/article/details/50248121

 

看别人的开源项目的时候发现,原来在终端可以打印带颜色的字符串的。。还蛮有意思的,只需要在待打印的字符串前面和后面分别加一串修饰字符就行了。

下面是C语言的一个例子:

 1 #include <stdio.h>
 2 
 3 #define ANSI_COLOR_RED     "\x1b[31m"
 4 #define ANSI_COLOR_GREEN   "\x1b[32m"
 5 #define ANSI_COLOR_YELLOW  "\x1b[33m"
 6 #define ANSI_COLOR_BLUE    "\x1b[34m"
 7 #define ANSI_COLOR_MAGENTA "\x1b[35m"
 8 #define ANSI_COLOR_CYAN    "\x1b[36m"
 9 #define ANSI_COLOR_RESET   "\x1b[0m"
10 
11 int main() {
12 
13   printf(ANSI_COLOR_RED     "This text is RED!"     ANSI_COLOR_RESET "\n");
14   printf(ANSI_COLOR_GREEN   "This text is GREEN!"   ANSI_COLOR_RESET "\n");
15   printf(ANSI_COLOR_YELLOW  "This text is YELLOW!"  ANSI_COLOR_RESET "\n");
16   printf(ANSI_COLOR_BLUE    "This text is BLUE!"    ANSI_COLOR_RESET "\n");
17   printf(ANSI_COLOR_MAGENTA "This text is MAGENTA!" ANSI_COLOR_RESET "\n");
18   printf(ANSI_COLOR_CYAN    "This text is CYAN!"    ANSI_COLOR_RESET "\n");
19 
20   return 0;
21 }

 

在终端的运行结果如下图所示:

这里写图片描述

其它更多的颜色可以参考:ANSI escape code

对于其他的编程语言也是一样的。

参考链接

1.http://stackoverflow.com/questions/3219393/stdlib-and-colored-output-in-c

posted @ 2018-09-07 15:05  dolinux  阅读(272)  评论(0)    收藏  举报