简体   繁体   English

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

[英]how to recognize string with color code with strncmp in c?

I have two programs in C:我在 C 中有两个程序:
a client and a server.一个客户端和一个服务器。

I'm not going to develop all the details of the code, things work fine.我不打算开发代码的所有细节,一切正常。 Except for this point: I want my server to send colored acknowledgment messages and my client to identify them.除了这一点:我希望我的服务器发送彩色确认消息并让我的客户端识别它们。

On the server the lines look like this:在服务器上,这些行如下所示:

    //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

And I wonder what code should I use to detect the acknowledgment on the client:我想知道我应该使用什么代码来检测客户端上的确认:

    //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);
    }

Things don't work.事情行不通。 I wonder what should I put instead of "\x1b[31m220",11 in the client to make things work.我想知道我应该在客户端中放置什么而不是"\x1b[31m220",11以使事情正常进行。 I suspect some characters of the color code to be interpreted and therefor to disappear from the string, but which ones?我怀疑颜色代码的某些字符会被解释并因此从字符串中消失,但是哪些字符呢?


There is an explanation of the color code here: stdlib and colored output in C这里有颜色代码的解释: stdlib and coloured output in C

"\x1b[31m220" has 8 characters , not 11. strncmp is going to fail at 9th character which is '\0' in this string and '\x1B' in the buffer. "\x1b[31m220"8 个字符,而不是 11 strncmp将在第 9 个字符处失败,即此字符串中的'\0'和缓冲区中的'\x1B'

Make your life easier and let compiler calculate the sizes for you:让您的生活更轻松,让编译器为您计算大小:

#define COLOURCODE "\x1b[31m220"

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

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

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