gpt4 book ai didi

带有颜色的 C fprintf

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:25:12 24 4
gpt4 key购买 nike

有没有一种方法可以在 Ubuntu Linux 上使用 C 编程语言将彩色文本打印到文件,您可以将颜色代码与 printf() 一起使用并将彩色文本打印到控制台或终端窗口,但是如何将文本打印到带有颜色的文本文件?

最佳答案

我正在使用这个解决方案,如果您喜欢流和 C++,它会非常简洁

#include <cstdlib>
#include <iostream>
#include <sstream>

namespace sps {
namespace colors {
enum color {
none = 0x00,
black = 0x01,
red = 0x02,
green = 0x03,
yellow = 0x04,
blue = 0x05,
magenta = 0x06,
cyan = 0x07,
white = 0x08
};
}
namespace faces {
enum face {
normal = 0x00,
bold = 0x01,
dark = 0x02,
uline = 0x04,
invert = 0x07,
invisible = 0x08,
cline = 0x09
};
}

/**
* Generate string for color codes for std::iostream's
*
* @param foreground
* @param background
*
* @return
*
* Usage:
*
* using namespace sps;
* std::cout << "These words should be colored [ "
* << set_color(colors::red) << "red "
* << set_color(colors::green) << "green "
* << set_color(colors::blue) << "blue"
* << set_color() << " ]" << std::endl;
*
*/
static inline std::string set_color(sps::colors::color foreground = sps::colors::none,
sps::colors::color background = sps::colors::none) {
std::stringstream s;
s << "\033[";
if (!foreground && ! background){
s << "0"; // reset colors if no params
}
if (foreground) {
s << 29 + foreground;
if (background) s << ";";
}
if (background) {
s << 39 + background;
}
s << "m";
return s.str();
}

/**
*
*
* @param face
*
* @return
*/
static inline std::string set_face(sps::faces::face face = sps::faces::normal) {
std::stringstream s;
s << "\033[";
if (!face) {
s << "0"; // reset face
}
if (face) {
s << face;
}
s << "m";
return s.str();
}
}

int main(int agrc, char* argv[])
{
using namespace sps;
std::cout << "These words should be colored [ "
<< set_color(colors::red) << "red "
<< set_color(colors::green) << "green "
<< set_color(colors::blue) << "blue "
<< set_color(colors::cyan) << "cyan "
<< set_color(colors::magenta) << "magenta "
<< set_color(colors::yellow) << "yellow"
<< set_color() << " ]" << std::endl;
return EXIT_SUCCESS;
}

关于带有颜色的 C fprintf,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36314690/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com