Color text in terminal applications in UNIX [dupli

2019-01-03 08:17发布

This question already has an answer here:

I started to write a terminal text editor, something like the first text editors for UNIX, such as vi. My only goal is to have a good time, but I want to be able to show text in color, so I can have syntax highlighting for editing source code.

How can I achieve this? Is there some special POSIX API for this, or do I have to use ncurses? (I'd rather not)

Any advice? Maybe some textbooks on the UNIX API?

标签: c unix terminal
4条回答
狗以群分
2楼-- · 2019-01-03 08:20

Use ANSI escape sequences. This article goes into some detail about them. You can use them with printf as well.

查看更多
来,给爷笑一个
3楼-- · 2019-01-03 08:35

This is a little C program that illustrates how you could use color codes:

#include <stdio.h>

#define KNRM  "\x1B[0m"
#define KRED  "\x1B[31m"
#define KGRN  "\x1B[32m"
#define KYEL  "\x1B[33m"
#define KBLU  "\x1B[34m"
#define KMAG  "\x1B[35m"
#define KCYN  "\x1B[36m"
#define KWHT  "\x1B[37m"

int main()
{
    printf("%sred\n", KRED);
    printf("%sgreen\n", KGRN);
    printf("%syellow\n", KYEL);
    printf("%sblue\n", KBLU);
    printf("%smagenta\n", KMAG);
    printf("%scyan\n", KCYN);
    printf("%swhite\n", KWHT);
    printf("%snormal\n", KNRM);

    return 0;
}
查看更多
放我归山
4楼-- · 2019-01-03 08:35

You probably want ANSI color codes. Most *nix terminals support them.

查看更多
唯我独甜
5楼-- · 2019-01-03 08:36

Here's another way to do it. Some people will prefer this as the code is a bit cleaner (there are no %s and a RESET color to end the coloration).

#include <stdio.h>

#define RED   "\x1B[31m"
#define GRN   "\x1B[32m"
#define YEL   "\x1B[33m"
#define BLU   "\x1B[34m"
#define MAG   "\x1B[35m"
#define CYN   "\x1B[36m"
#define WHT   "\x1B[37m"
#define RESET "\x1B[0m"

int main()
{
  printf(RED "red\n" RESET);
  printf(GRN "green\n" RESET);
  printf(YEL "yellow\n" RESET);
  printf(BLU "blue\n" RESET);
  printf(MAG "magenta\n" RESET);
  printf(CYN "cyan\n" RESET);
  printf(WHT "white\n" RESET);

  return 0;
}

This way, it's easy to do something like:

printf("This is " RED "red" RESET " and this is " BLU "blue" RESET "\n");
查看更多
登录 后发表回答