如何在 c 中使用 strncmp 识别带有颜色代码的字符串?

how to recognize string with color code with strncmp in c?

我在 C:
中有两个程序 一个客户端和一个服务器。

我不打算开发代码的所有细节,一切正常。除了这一点: 我希望我的服务器发送 colored 确认消息并让我的客户端识别它们。

在服务器上,行如下所示:

    //server side there there is:
    FILE * stream; // for the socket

    fprintf(stream,"\x1b[31m220\x1B[0m GET command received please type the file name\n");
    //here stream refers to a classic BSD socket which connect client to server
    //\x1b[31m colors text in red
    //\x1B[0m put back text color to normal

而且我想知道应该使用什么代码来检测客户端的确认:

    //Client side there is:
    FILE * stream; // for the socket (client side)
    char buffer[100]; //to receive the server acknowledgment

    //fgets put the received stream text in the buffer:
    fgets (buffer , sizeof buffer, stream);
    
    //Here strncmp compares the buffer first 11 characters with the string "\x1b[31m220"
    if (strncmp (buffer, "\x1b[31m220",11)== 0)
    {
    printf("\x1B[48;5;%dmCommand received\x1B[0m%s\n",8,buffer);
    }

事情不奏效。我想知道我应该在客户端中放置什么而不是 "\x1b[31m220",11 来使事情正常进行。我怀疑颜色代码的某些字符会被解释并因此从字符串中消失,但是哪些字符?


这里有颜色代码的解释: stdlib and colored output in C

"\x1b[31m220"8 个字符 ,而不是 11。strncmp 将在第 9 个字符处失败,即此字符串中的 '[=12=]' 并且'\x1B' 在缓冲区中。

让您的生活更轻松,让编译器为您计算大小:

#define COLOURCODE "\x1b[31m220"

if (strncmp (buffer, COLOURCODE, sizeof(COLOURCODE) - 1)== 0)