stdlib y salida coloreada en C


Estoy haciendo una aplicación simple que requiere salida de color. ¿Cómo puedo hacer que mi salida sea coloreada como emacs y bash?

No me importa Windows, ya que mi aplicación es solo para sistemas UNIX.

Author: mdml, 2010-07-10

7 answers

Todos los emuladores de terminales modernos usan códigos de escape ANSI para mostrar colores y otras cosas.
No te molestes con las bibliotecas, el código es muy simple.

Más información es aquí .

Ejemplo en 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;
}
 234
Author: Andrejs Cainikovs,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-07-10 17:20:30

Tratar con secuencias de color puede ser complicado y diferentes sistemas pueden usar diferentes Indicadores de Secuencia de color.

Te sugiero que intentes usar ncurses. Además del color, ncurses puede hacer muchas otras cosas interesantes con la interfaz de usuario de la consola.

 11
Author: ,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-07-10 13:50:02

Puede generar códigos de control de color especiales para obtener una salida de terminal de color, aquí hay un buen recurso sobre cómo imprimir colores.

Por ejemplo:

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

EDITAR: Mi original utiliza códigos de color prompt, que no funciona :( Este lo hace (lo probé).

 8
Author: Stephen,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-07-10 13:57:47

Puede asignar un color a cada funcionalidad para que sea más útil.

#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");
}

Como wise puede seleccionar diferentes códigos de color y hacer esto más genérico.

 6
Author: Praveen S,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-07-10 14:00:58

Si usa el mismo color para todo el programa , puede definir la función 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;
   }
 2
Author: alhelal,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-02-01 17:17:45

Porque no se puede imprimir un carácter con formato de cadena. También puede pensar en agregar un formato con algo como esto

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

f es formato como en printf

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

Se imprimirá blue bar

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

Se imprimirá red 97

 1
Author: baz,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-06-04 03:21:46
#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;
}

Leyendo Wikipedia :

  • \x1b [0m restablece todos los atributos
  • \x1b [31m establece el color del primer plano en rojo
  • \x1b[44m establecería el fondo en azul.
  • ambos: \x1b[31;44m
  • ambos pero invertidos: \x1b[31;44;7m
  • recuerde reiniciar después \x1b[0m...
 0
Author: Ladon,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-08-21 11:06:20