Search code examples
cstringsizeofstrlen

Find string in buffer


This function browse through the strings added into the buffer and search for the specified field. If the field is found in the buffer, the pointer to the assigned content is returned. If the specified field is not found inside the buffer a pointer to a "?" string is delivered.

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

char buf[256] = "ID=1234 Name=Manavendra Nath Manav Age=30";

const char * get_info (const char *name)
{
    unsigned   nl;
    const char *p, *e;

    if(name!=NULL)
    {
        nl = strlen(name);
        for (p = buf, e = p + strlen(buf) ; p < e && p[0] ; p += strlen(p) + 1) {
            printf("p = %s\tname = %s\te = %s\n", p, name, e);
            if (strncmp (p, name, nl) == 0 && p[nl] == '=')
                return (p + nl + 1);
        }
    }
    return "?";
}

int main()
{
    printf("strlen(buf) = %d\n", strlen(buf));
    printf("%s\n", get_info("Nath"));
    return 0;
}

After execution, I am always getting ? as output, what is wrong with the code? On a second note, would it be advisable to replace strlen with sizeof in the above code? sizeof(buf) returns 256.

manav@os-team:~/programs/test$ ./a.out
strlen(buf) = 21
p = Manavendra Nath Manav       name = Nath     e =
?

EDIT: Sorry, I didn't updated about p[nl] == '=' before. If the buffer is like char buf[256] = "ID=1234 Name=Manavendra Nath Manav Age=30"; then get_info("Name") should return Manavendra Nath Manav.


Solution

  • The return inside the loop can only execute if p[nl] equals '=':

            if (strncmp (p, name, nl) == 0 && p[nl] == '=')
                                           ^^^^^^^^^^^^^^^
    

    However, there are no '=' in your string, so it's the final return "?" that always gets executed.