Colours

From Hamsterworks Wiki!

Jump to: navigation, search

White characters on a black background - how boring! Here is how to add a splash of colour to your next C programs.

Although Linux has a set of library called 'ncurses' that allows you to control terminals the 'proper way' we can short-circuit all that and see how it all works.

Programs send characters to the terminal to update the display, much like how you can send characters to a program by typing on the keyboard. To make the terminal show text in different colours (and other stuff) we need to send it a special sequence of characters, called 'escape codes'. Escape codes are called this because they start with the "Esc" character, which in C is encoded with "\033".

Escape codes can differ for different terminals, but the ones used here should work on most common terminals.

To change colour call setcolour() passing it a number from zero to seven. I've also included the 'clear()' function to clear the screen, and the 'position()' function to move the cursor to a different row or column, allowing you to jump around the screen and put text just where you want it.

If you ever find that you leave your terminal with unusable settings try typing "tput reset" to reset the terminal its standard settings.

#include <stdio.h>

void position(int col, int row) {
  printf("\033[%02i;%02iH", row+1, col+1);
}

void clear() {
  printf("\033[H\033[2J");
}

void setColour(unsigned char i) {
  printf("\033[00;3%cm", '0'+i);
}

int main(int argc, char *argv[]) {
  clear();
  position(20,0); setColour(1); printf("Hello world"); 
  position(20,1); setColour(5); printf("in"); 
  position(20,2); setColour(3); printf("colour\n"); 
  setColour(2); 
  return 0;
}

Personal tools