如何以跨平台方式以彩色打印到控制台?

时间:2010-03-01 01:33:00

标签: linux macos console colors

如何在Mac OS X和Linux上使用“printf”输出彩色文本?

3 个答案:

答案 0 :(得分:29)

您可以使用ANSI颜色代码。这是一个示例程序:

#include <stdio.h>

int main(int argc, char *argv[])
{
  printf("%c[1;31mHello, world!\n", 27); // red
  printf("%c[1;32mHello, world!\n", 27); // green
  printf("%c[1;33mHello, world!\n", 27); // yellow
  printf("%c[1;34mHello, world!\n", 27); // blue
  return 0;
}

27escape个字符。如果您愿意,可以使用\e

网上列出了所有代码。 Here is one

答案 1 :(得分:4)

另一种选择是:

# Define some colors first (you can put this in your .bashrc file):
red='\e[0;31m'
RED='\e[1;31m'
blue='\e[0;34m'
BLUE='\e[1;34m'
cyan='\e[0;36m'
CYAN='\e[1;36m'
green='\e[0;32m'
GREEN='\e[1;32m'
yellow='\e[0;33m'
YELLOW='\e[1;33m'
NC='\e[0m'
#################

然后你可以输入终端:

echo -e "${RED}This is an error${NC}"
echo -e "${YELLOW}This is a warning${NC}"
echo -e "${GREEN}Everythings fine!${NC}"

最后不要忘记$ {NC}。 NC代表“无颜色”,这意味着在您的句子之后,它将恢复为正常颜色。如果你忘了它,之后的整个提示和命令将是你指定的颜色(当然你可以输入'echo -e“$ {NS}”'来改回它)。

答案 2 :(得分:2)

为获得最佳可移植性,请查询terminfo数据库。在shell中,

colors=(black red green yellow blue magenta cyan white)
for ((i = 0; i < ${#colors[*]}; i++)); do
    ((j=(i+1)%${#colors[*]}))
    printf '%s%s%s on %s%s\n' "$(tput setaf $i)" "$(tput setab $j)" \
            "${colors[i]}" "${colors[j]}" "$(tput op)"
done

将打印出来

black on red
red on green
green on yellow
yellow on blue
blue on magenta
magenta on cyan
cyan on white
white on black

但颜色。