0

Earlier somebody posted a question regarding a bot they were developing for IRC.

They mentioned that upon sending the server a command to list channels the server would reply with raw data of all the channels and at the end of that list would be ENDOFLIST. They also said that they do not know the actual length of the data being sent and cannot rely purely on a function like strstr because if a user named a channel ENDOFLIST the string would terminate there. They then asked if it was possible to determine when the true ENDOFLIST came in the buffer of raw data they had.

My idea was just to iterate through the data until the very last instance of ENDOFLIST was found, and then just go off the location of that final instance. Before I could post my answer the person who asked the question deleted it, but I am still wondering if my solution is a viable one.

This is what I came up with:

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

/*function I wrote for myself a while back to find substrings*/
int strsbstr(const char *str, const char *sbstr)
{
    char *sbstrlc;

    if(!(strcmp(str, sbstr))) return 0;
    if(!(sbstrlc = strstr(str, sbstr))) return -1;
    return (int) (sbstrlc - str);
}

int main(int argc, char *argv[])
{
    int index = 0, location = 0;
    char *string;

    if(!(string = malloc(37))) return 0x00;
    strcpy(string, "FOOBARENDOFLISTENDOFLISTENDOFLISTFOO");  //string contains "ENDOFLIST" three times
    index = strsbstr(string, "ENDOFLIST");                   //index holds position of first occurence of "ENDOFLIST" within the string
    while(index != -1)                                       //loop through the rest of the string until the final "ENDOFLIST" is found
    {
        location = index + location + strlen("ENDOFLIST");
        index = strsbstr(string + location, "ENDOFLIST");
    }
    /*
    the variable 'location' now holds the position of the final char of the last occurence of "ENDOFLIST" within the string
    and 'location - strlen("ENDOFLIST")' would yield the position of the first char of the last occurence of "ENDOFLIST" 
    within the string
    */
    free(string);
    return 0;
}

I'm sure many of you who frequent the C section of this site have seen this post earlier today. I just wanted to get some input if this would solve the problem that the asker was having, and if it's viable.

Even thinking of it practically I'm almost 100% sure that IRC channels cannot have the same name anyway so the loop might not even be needed. It should only have to check if "ENDOFLIST" occurs in the string once more after the first time right?

4

0 に答える 0