我刚刚在 C 中玩弄了一些代码,一个非常基本的程序示例如下所示,很明显,它使用 ls 系统命令列出了目录。
#include <stdio.h>
int main (void) {
system("ls -l -d */");
printf("I've just listed the directories :-)\n");
return 0;
}
Run Code Online (Sandbox Code Playgroud)
这运行良好,但它以单色显示 ls 输出,而 Bash 将使用目录(或文件,如果我包含文件)的颜色输出列表。如何让我的 C 代码使用 bash 颜色?谢谢
ls默认别名为:ls --color=auto所以当ls在支持颜色的终端中时,它使用颜色代码。
一个system()让你的别名不计算调用不会在bash会话发生。我也不确定自动检测会发生什么,所以我会通过热线命令来强制彩色输出:
system("ls --color=always -l -d */");
Run Code Online (Sandbox Code Playgroud)
我已经测试过了,它有效。--color=auto也有效,那可能更安全。
即使不在 Csystem()调用中,这种现象也可能发生。我和其他人也遇到过类似的问题watch。运行watch ls -l,你将看不到颜色。还有一个解释为什么--colour=auto不总是有效。