2

I've just been fooling around with some code in C, an example of a really basic program is as follows which just, obviously, lists the directories using the ls system command.

#include <stdio.h>

int main (void) {
    system("ls -l -d */");
    printf("I've just listed the directories :-)\n");
    return 0;
}

This runs fine, but it shows the ls output in monochrome, whereas Bash would output the list using colors for the directories (or files if I included files). How can I make my C code use the bash colors? Thanks

Braiam
  • 66,947
  • 30
  • 177
  • 264

1 Answers1

8

ls is aliased by default as: ls --color=auto so when ls is in a terminal that supports colour, it uses colour codes.

A system() call doesn't happen in a bash session so your aliases aren't evaluated. I'm also not sure what would happen with the automatic detection so I would make it force colourised output by hotwiring the command:

system("ls --color=always -l -d */");

I've tested that and it works. --color=auto worked too and that might be safer.

This phenomenon can happen even without it being in a C system() call. I've been through a similar problem with watch with somebody else. Run watch ls -l and you won't see colours. There's also an explanation on why --colour=auto doesn't always work.

Oli
  • 289,791
  • 117
  • 680
  • 835
  • 1
    @oli `--color=auto` sets `color_if_tty` which [tries to determine if the current terminal is a tty](http://git.savannah.gnu.org/gitweb/?p=coreutils.git;a=blob;f=src/ls.c;h=25e10fa74bf0622ae57b1f4e203e2dbdbf5da0f9;hb=HEAD#l1901) before using colors. – Braiam Jun 01 '14 at 13:36
  • 1
    and [here is how](http://man7.org/linux/man-pages/man3/isatty.3.html): "The isatty() function tests whether fd is an open file descriptor referring to a terminal." – Braiam Jun 01 '14 at 13:51