programing

stdlib 및 컬러 출력(C)

coolbiz 2022. 11. 23. 21:11
반응형

stdlib 및 컬러 출력(C)

컬러 출력을 필요로 하는 간단한 어플리케이션을 만들고 있습니다.출력에 emacs나 bash와 같은 색을 입히려면 어떻게 해야 하나요?

제 애플리케이션은 UNIX 시스템 전용이기 때문에 Windows에 대해서는 신경 쓰지 않습니다.

최신 터미널 에뮬레이터는 모두 ANSI 이스케이프 코드를 사용하여 색상 및 기타 정보를 표시합니다.
도서관은 신경 쓰지 마, 암호는 정말 간단해.

자세한 내용은 이쪽입니다.

C의 예:

#include <stdio.h>

#define ANSI_COLOR_RED     "\x1b[31m"
#define ANSI_COLOR_GREEN   "\x1b[32m"
#define ANSI_COLOR_YELLOW  "\x1b[33m"
#define ANSI_COLOR_BLUE    "\x1b[34m"
#define ANSI_COLOR_MAGENTA "\x1b[35m"
#define ANSI_COLOR_CYAN    "\x1b[36m"
#define ANSI_COLOR_RESET   "\x1b[0m"

int main (int argc, char const *argv[]) {

  printf(ANSI_COLOR_RED     "This text is RED!"     ANSI_COLOR_RESET "\n");
  printf(ANSI_COLOR_GREEN   "This text is GREEN!"   ANSI_COLOR_RESET "\n");
  printf(ANSI_COLOR_YELLOW  "This text is YELLOW!"  ANSI_COLOR_RESET "\n");
  printf(ANSI_COLOR_BLUE    "This text is BLUE!"    ANSI_COLOR_RESET "\n");
  printf(ANSI_COLOR_MAGENTA "This text is MAGENTA!" ANSI_COLOR_RESET "\n");
  printf(ANSI_COLOR_CYAN    "This text is CYAN!"    ANSI_COLOR_RESET "\n");

  return 0;
}
#include <stdio.h>

#define BLUE(string) "\x1b[34m" string "\x1b[0m"
#define RED(string) "\x1b[31m" string "\x1b[0m"

int main(void)
{
    printf("this is " RED("red") "!\n");

    // a somewhat more complex ...
    printf("this is " BLUE("%s") "!\n","blue");

    return 0;
}

Wikipedia 읽기:

  • \x1b[0m은 모든 속성을 리셋합니다.
  • \x1b[31m은 전경색을 빨간색으로 설정한다.
  • \x1b [ 44m ]배경을 파란색으로 설정합니다.
  • 둘 다 : \x1b[31;44m]
  • 양쪽 반전: \x1b[31;44;7m]
  • \x1b[0m...] 후에 리셋하는 것을 잊지 마십시오.

모든 기능에 한 가지 색상을 할당하여 더 유용하게 사용할 수 있습니다.

#define Color_Red "\33[0:31m\\]" // Color Start
#define Color_end "\33[0m\\]" // To flush out prev settings
#define LOG_RED(X) printf("%s %s %s",Color_Red,X,Color_end)

foo()
{
LOG_RED("This is in Red Color");
}

마찬가지로 다른 색상 코드를 선택하여 보다 일반적인 색상을 만들 수 있습니다.

특수 컬러 컨트롤 코드를 출력하여 컬러 터미널 출력을 얻을 수 있습니다. 여기 컬러 인쇄 방법에 대한 유용한 자료가 있습니다.

예를 들어 다음과 같습니다.

printf("\033[22;34mHello, world!\033[0m");  // shows a blue hello world

편집: 원래 제품은 프롬프트 색상 코드를 사용했지만 작동하지 않습니다:(이 제품은 테스트했습니다).

문자열 형식이 있는 문자를 인쇄할 수 없기 때문입니다.이와 같은 방법으로 형식을 추가하는 것도 생각해 볼 수 있습니다.

#define PRINTC(c,f,s) printf ("\033[%dm" f "\033[0m", 30 + c, s)

f의 형식과 같습니다.printf

PRINTC (4, "%s\n", "bar")

인쇄하다blue bar

PRINTC (1, "%d", 'a')

인쇄하다red 97

색 시퀀스를 다루면 복잡해지고 시스템에 따라 색 시퀀스 인디케이터가 다를 수 있습니다.

ncurses를 써보는 게 좋을 것 같아ncurses는 색상 외에도 콘솔 UI로 많은 깔끔한 작업을 수행할 수 있습니다.

프로그램 전체에 동일한 색상을 사용하는 경우,printf()기능.

   #include<stdio.h>
   #define ah_red "\e[31m"
   #define printf(X) printf(ah_red "%s",X);
   #int main()
   {
        printf("Bangladesh");
        printf("\n");
        return 0;
   }

언급URL : https://stackoverflow.com/questions/3219393/stdlib-and-colored-output-in-c

반응형