简体   繁体   English

C代码改变终端文本颜色; 如何恢复默认值? Linux的

[英]C code changes terminal text color; how to restore defaults? Linux

I have a C file running on Linux. 我在Linux上运行了一个C文件。 It prints some lines in red (failures) and some in green (passes). 它以红色(失败)打印一些线条,以绿色(通过)打印一些线条。 As you might expect, it uses escape codes in the printf statements as follows: 正如您所料,它在printf语句中使用转义码,如下所示:

#define BLACK  "\033[22;30m"
#define GREEN  "\033[22;31m"

printf(GREEN "this will show up green" BLACK "\n");

If the BLACK at the end wasn't there, the terminal text will continue to be green for everything. 如果最后的BLACK不存在,终端文本将继续为所有内容为绿色。 In case you didn't catch it, that's fine for a terminal window with a non-black background, but otherwise you'll end up with black-on-black. 如果你没有抓住它,那对于具有非黑色背景的终端窗口来说没问题,但是否则你最终会得到黑底黑字。 Not good! 不好! Running the program has this problem, as does capturing the output in a text file and then viewing the file with "more" or "less". 运行程序有这个问题,捕获文本文件中的输出,然后使用“更多”或“更少”查看文件也是如此。

Is there a code to restore defaults instead of specifying a color at the end of the printf statement? 是否有代码恢复默认值而不是在printf语句的末尾指定颜色? This needs to be in C, but I would be interested in reading about other approaches. 这需要在C中,但我有兴趣阅读其他方法。

Update: Thank you all. 更新:谢谢大家。 Your responses helped me find even more useful info elsewhere. 您的回复帮助我在其他地方找到更有用的信息。 I updated my macros as follows (note 31 is for red and I fixed that typo below): 我更新了我的宏如下(注意31是红色的,我修正了下面的拼写错误):

#define RESET_COLOR "\e[m"
#define MAKE_GREEN "\e[32m"

printf(MAKE_GREEN "this will show up green" RESET_COLOR "\n");

I found the following links helpful in understanding how these codes work: 我发现以下链接有助于理解这些代码的工作原理:

http://www.phwinfo.com/forum/comp-unix-shell/450861-bash-shell-escapes-not-working-via-putty-ssh.html explains what these escape sequences do, and to use ncurses if portability is needed. http://www.phwinfo.com/forum/comp-unix-shell/450861-bash-shell-escapes-not-working-via-putty-ssh.html解释了这些转义序列的作用,并在可移植性时使用ncurses需要。

http://www.linuxselfhelp.com/howtos/Bash-Prompt/Bash-Prompt-HOWTO-6.html http://www.linuxselfhelp.com/howtos/Bash-Prompt/Bash-Prompt-HOWTO-6.html

http://bluesock.org/~willg/dev/ansi.html shows even more escape sequences; http://bluesock.org/~willg/dev/ansi.html显示更多的转义序列; useful to get the big picture 有用的了解大局

Try using: 尝试使用:

#define RESETCOLOR "\033[0m"

That should reset it to the defaults. 这应该将其重置为默认值。

More about these terminal codes can be found here: http://en.wikipedia.org/wiki/ANSI_escape_code 有关这些终端代码的更多信息,请访问: http//en.wikipedia.org/wiki/ANSI_escape_code

"\033[0m"

见这里: http//en.wikipedia.org/wiki/ANSI_color

type reset in the terminal. 在终端中键入reset

There is a binary found in Linux and OSX called reset. Linux和OSX中有一个名为reset的二进制文件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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