Search code examples
cstringcolorsstrncmp

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


I have two programs in 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. 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


Solution

  • "\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.