green: a tiny util for turning every third line green

Yesterday I told you about the python module ‘termcolor’, which could be used to print coloured output onto an ANSI terminal. I suggested that every third line should be coloured, to aid readability. Today, I’ll show you how to do it in C. I call the utility “green”. And example output is shown below:


The figure above is the result of running the command green <green.c. The code is so short that I present it below:



#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"

#define BUF_SIZE 1024

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

  char buffer[BUF_SIZE] ;
  //char * begin;
  int i = 0;
  size_t nread;

  while(nread = fread(buffer, 1, BUF_SIZE, stdin)){
    for(int j =0; j< nread; j++) {
      int c = buffer[j];
      if(c == '\n') {
        if(i==0) {printf(ANSI_COLOR_RESET);}
        i = (1+i) % 3;
        if(i==0) {printf(ANSI_COLOR_GREEN);}
      } else { putchar(c);}

  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_CYAN    "This text is CYAN!"    ANSI_COLOR_RESET "\n");
  return 0;

Save it as green.c, and compile is using the command:

gcc -std=gnu99 -o green green.c

You can then redirect stdin to stdout. If you want to pipe the output through less, remember that you need raw mode:

green < myfile | less - r

Bon apetite.


About mcturra2000

Computer programmer living in Scotland.
This entry was posted in Uncategorized. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s