[英]How to color output in C for cross-platform app
I am new and I know how to color output only in Unix/Linux systems:我是新手,我只知道如何在 Unix/Linux 系统中为 output 着色:
#include <stdio.h>
int main(void) {
printf("\033[1;31mRed Message\033[0m.");
}
But this is not works in Windows cmd.exe, only in Unix terminal.但这不适用于 Windows cmd.exe,仅适用于 Unix 终端。
I am writing cross-platform app and want to know how can I do this in Windows cmd.exe too.我正在编写跨平台应用程序,想知道如何在 Windows cmd.exe 中执行此操作。
This also does not works:这也不起作用:
1. 1.
#include <stdio.h>
int main(void) {
printf("%c[1;31mRed Message%c[0m", 27, 27);
}
2. 2.
#include <stdio.h>
int main(void) {
printf("[1;31m Red Message [0m");
}
This works, but I think this is just a bug:这有效,但我认为这只是一个错误:
If I type system("");
如果我输入system("");
before printf
then it works.在printf
之前,它可以工作。
#include <stdio.h>
int main(void) {
system("");
printf("\033[1;31m Red Message \033[0m");
}
Thanks谢谢
If you want to make your library crossplatform, I would use the following approach: Have a library, with the same functions, let's say: void printInRed(const char* string)
.如果你想让你的库跨平台,我会使用以下方法:拥有一个具有相同功能的库,比如说: void printInRed(const char* string)
。 (In a headerfile) After that you write two or more implementations. (在头文件中)之后您编写两个或多个实现。 One for windows: windows 一个:
//TODO: Errorchecking
void printInRed(const char* string){
HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
//TODO: Extract magic number
//See https://stackoverflow.com/a/4053879/13912132
SetConsoleTextAttribute(hConsole, 12);
puts(string);
}
And another one for unix-like OS:另一个适用于类 unix 的操作系统:
//TODO: Errorchecking
void printInRed(const char* string){
printf("\033[1;31m%s\033[0m.", string);
}
Then you can check at compile time, which version to compile.然后您可以在编译时检查要编译的版本。 The first approach is to use #ifdef
s, but this will make the code a bit messy.第一种方法是使用#ifdef
,但这会使代码有点混乱。
Another approach would be to use a build-system like CMake
to select at build time, which one to build.另一种方法是在构建时使用CMake
到 select 之类的构建系统,其中一个要构建。 A buildsystem requires a bit of learning, but will help you to make maintaining a crossplatform library simpler.构建系统需要一些学习,但会帮助您更简单地维护跨平台库。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.