Skip to content

Instantly share code, notes, and snippets.

@Satharus
Last active July 17, 2022 17:10
Show Gist options
  • Save Satharus/c5dc643e6fc82a95cdc3e215fe848bd5 to your computer and use it in GitHub Desktop.
Save Satharus/c5dc643e6fc82a95cdc3e215fe848bd5 to your computer and use it in GitHub Desktop.
An example for using ANSI escape sequences to change foreground and background colours in a terminal.
#include <stdio.h>
#include <string.h>
/*
Terminal text foreground and background colours can be changed using ANSI escape codes.
If an escape character followed by a certain sequence is printed to STDOUT, the terminal will change the fore/background colour.
- Foregroud colour sequence: ESC[38;5;{COLOUR}m replace {COLOUR} with one of the numbers from the 8-bit ANSI colour lookup table.
- Background colour sequence: Do the exact same as above but use 48 instead of 38. Making the sequence ESC[48;5;{COLOUR}m
- The ASCII value for ESC is 0x1B or 27 in decimal
- You can also reset colours by printing ESC[0m
More info: https://en.wikipedia.org/wiki/ANSI_escape_code#Colors
*/
void printhelp()
{
printf("Pass either of the following arguments:\n\n"
"p - Print the 256 colour palette\n"
"l - Print 64 lines, each representing four of the colours\n");
}
int main(int argc, char *argv[])
{
//Literally just overengineering this. You know, *nix style.
if (argc < 2)
{
printhelp();
return 1;
}
//Printing the palette
if (strncmp(argv[1], "p", 1) == 0)
{
//Padding for the main 16 colours
printf(" ");
//Print the main 16 colours, using 48 to select the background colour.
for (int i = 0; i < 16; i++)
{
printf("\x1B[48;5;%dm ", i);
}
//Reset colours and print two empty lines
printf("\x1B[0m\n\n");
//Print the 8-bit colour palette
for (int i = 16, j = 0; i < 232; i++)
{
printf("\x1B[48;5;%dm ", i);
//Print new line after printing new colours
if (j == 35)
{
j = -1;
printf("\x1B[0m\n");
}
j++;
}
//Reset colours and print an empty line
printf("\x1B[0m\n");
//Padding for the grayscale palette
for (int i = 0; i < 12; i++) printf(" ");
//Print the grayscale palette
for (int i = 232; i < 256; i++)
{
printf("\x1B[48;5;%dm ", i);
}
printf("\x1B[0m\n");
}
//Printing colorful lines!
else if (strncmp(argv[1], "l", 1) == 0)
{
//Iterate the colours one by one, print the same text. Using 38 this time to select the foreground colour.
for (int i = 0, j = 0; i < 256; i+=2)
{
printf("\x1B[38;5;%dmColourful", i);
printf("\x1B[38;5;%dmtext!! ", i+1);
if (j++ == 1)
{
j = 0;
printf("\n");
}
}
}
//Invalid option, print help and return
else
{
printhelp();
return 1;
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment