简体   繁体   中英

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!

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

尝试调用ls --color=autols --color=always来显示带颜色的ls

This is likely due to a bash configuration file somewhere in your system aliasing "ls" to "ls --color".

Using "ls --color" in your program should work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM