Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Output of C++ function system(command) does not show color in Linux terminal

When I directly run a command in my Linux terminal, say "ls", the output is with color. However, when I run a C++ program which calls system("ls"), the output does not have color.

Is there way to get the latter way to also display colored output?

Thanks!

like image 882
Larry Avatar asked Oct 24 '25 09:10

Larry


2 Answers

The answer for why there's no color lies here.

system() executes a command specified in command by calling /bin/sh -c command, and returns after the command has been completed.

sh -c ignores aliases. Perhaps somewhere you have an alias where ls means ls --color=auto.

So for example, if I do sh -c 'ls', I will get no color.

Proof:

wow ♪[01:04 AM][vnbraun@chernobyl ~]$ which ls
alias ls='ls --color=auto'
        /bin/ls
wow ♪[01:08 AM][vnbraun@chernobyl ~]$ sh -c 'which ls'
/bin/ls

Therefore, you can try doing system("ls --color=auto");.

You could run

 system("/bin/ls --color=auto");

But I don't think you really should run ls from your C++ program. Perhaps you want to use -some combination of- readdir(3), stat(2), nftw(3), glob(3), wordexp(3) etc etc....

I don't think that forking a shell which then runs /bin/ls is useful from a C++ program. There are simpler ways to achieve your goal (which I cannot guess).

You probably should read Advanced Linux Programming

like image 29
Basile Starynkevitch Avatar answered Oct 26 '25 23:10

Basile Starynkevitch