可以将输出文本的颜色调整为文本文件吗?

时间:2016-05-06 22:21:23

标签: c printf

我发现fprintf没有天生的能力来调整输出文本的颜色,而cprintf通过" conio.h"无法打印到文件(不是我能找到的)。

我希望能够在" data.text"中调整fprintf输出的颜色为绿色。文件。

static void cursor_position_callback(GLFWwindow* w, double x, double y)
{
    FILE *f = fopen("data.txt", "a");
    if (f==NULL)
    {
        printf("Error opening file!\n");
    }

    fprintf(f,"%0.3f: Cursor position: %f %f (%+f %+f)\n",
           glfwGetTime(),
           x, y, x - cursor_x, y - cursor_y);

    cursor_x = x;
    cursor_y = y;
    fclose(f);
}

输出将用于涉及眼手追踪功能的实验中的鼠标跟踪数据。非常感谢你的时间。

2 个答案:

答案 0 :(得分:3)

文件只是一个字节序列;它的内容永远不会有颜色。颜色仅在显示信息时出现(在监视器上或在纸上打印时)。但是,如果读取文件的程序知道如何正确地对文件内容作出反应,则选择要显示的颜色会受到文件中信息的影响。这实际上意味着您需要定义(或使用现有的)文件格式:关于如何构造和解释文件内容的规则。例如(忽略StackOverflow着色;这应该表示文本文件中的未着色文本):

Some of this text is <red>colored</red> in <blue>different</blue> ways.

现在,要显示此对象的程序必须查找<color> / </color>对的出现次数,并在显示所附文本之前相应地更改控制台颜色。请注意,如果要显示的文本本身可能包含<red>,则需要某种转义机制,例如确定<<将代表文字<

正如您所知,定义文件格式并不容易,您应该坚持使用已有解析器的既定格式。

答案 1 :(得分:0)

在通常的实践中,“文本”这个词经常被广泛使用(错误)。在C编程实践中,术语的严格含义也常常被称为“纯文本”格式(与“富文本”格式和其他一些文本格式相对)。让我们来看看这个简单的演示程序:

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
FILE* testfile;
    fprintf(stdout, "%c\x1b[31m",27);    
    fprintf(stdout, "===================TITLE=================\n");
    fprintf(stdout, "%c\x1b[0m", 27); 
    fprintf(stdout, "This is a plain text coloration test in C\n");

    if((testfile = fopen("test.txt", "r" )) == NULL){
        testfile = fopen("test.txt", "w" );
        if(testfile != NULL ){
            fprintf(testfile, "%c\x1b[31m",27);    
            fprintf(testfile, "===================TITLE=================\n");
            fprintf(testfile, "%c\x1b[0m", 27); 
            fprintf(testfile, "This is a plain text coloration test in C\n");    
            fclose(testfile);    
        }
    }
return 0;
}

只要fprintf写入stoutstderr,终端和shell就可以将ANSI / VT 100转义序列解释为颜色,但如果它写入常规文件而不是,这是写入文件的内容:

[31m===================TITLE=================
  [0mThis is a plain text coloration test in C