ls system command not showing terminal colors

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


Solution 1:

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.