printf输出字体颜色

时间:2020-12-21 04:44:11

printf输出字体颜色

 
有时候为了实现在终端输出的时候字体能够带颜色,并且可以产生简单的闪烁的功能,特写了下列的代码
实现hello world的带颜色的输出,并且每过一秒产生一个闪烁的功能.
(注:具体还得判断终端类型)
CODE:
#include<stdio.h>
#include<unistd.h>
#include<signal.h>
#include<stdlib.h>

int flag = 0;

void sig_int(int signum)
{
       if (flag ==1)
            fprintf(stderr, "\033[47;31mhello world\033[5m");
       fprintf(stderr,"\033[;\033[0m");
       fprintf(stderr,"\033[;\033[0m");
       printf("\n");
       exit(0);
}

int main()
{
       int i =0;
       structsigaction sig_act;
       sig_act.sa_handler= sig_int;
       sigemptyset(&sig_act.sa_mask);
       sig_act.sa_flags= 0;
       if(sigaction(SIGINT, &sig_act, NULL) < 0)
       {
            fprintf(stderr, "signal error\n");
            exit(1);
       }
       while (i++< 10)
       {
            fprintf(stderr, "\033[;\033[s");
            fprintf(stderr, "\033[47;31mhello world\033[5m");
             flag =0;
            sleep(1);
            fprintf(stderr, "\033[;\033[u");
            fprintf(stderr, "\033[;\033[K");
             flag =1;
            sleep(1);
       }

       fprintf(stderr,"\033[47;31mhello world\033[5m");
       fprintf(stderr,"\033[;\033[0m");
       printf("\n");
       return0;
}

该程序实现输出十次hello world然后退出.使用一个信号是为了还原默认的终端输出的颜色.
另外再讲讲如何输出颜色以及颜色的代码.

格式:

CODE:
printf("\033[字背景颜色;字体颜色m字符串\033[0m");  

printf("\033[47;31mhello world\033[5m");
47是字背景颜色, 31是字体的颜色, helloworld是字符串.  后面的\033[5m是控制码.

颜色代码:

QUOTE:
字背景颜色范围: 40--49              字颜色:30--39
            40:黑                           30:黑
              41: 红                    31: 红
              42: 绿                    32: 绿
               43: 黄                    33: 黄
               44:蓝                    34: 蓝
               45: 紫                    35: 紫
               46:深绿                   36:深绿