Re: [SLUG] evil C question! AAAGGHH!! help !!

From: Paul Braman (aeon@tampabay.rr.com)
Date: Wed Jun 20 2001 - 18:06:35 EDT


On Tue, 19 Jun 2001, Glen wrote:

> In another function, parse_comm_config():
>
> <snip>
> if(strstr(line, "PORT")){
> equal_ptr = strchr(line, '=');
> comm_settings.PORT = ++equal_ptr;
> comm_settings.PORT[strlen(comm_settings.PORT)-1] = '\0';
> equal_ptr = NULL;
> continue;
> }
> <snip>

Looks like a simple resource control problem. Let's assume that line
contains the following string (without quotes):

        "PORT=/dev/ttyS0"

You will have had to take care of the ending newline character yourself
and any possible leading spaces. The best way to parse this line and get
the information you desire is to do something like:

        if (!strncmp(line, "PORT", 4))
        {
                equal_ptr = strchr(line, '=');
                equal_ptr++;
                comm_settings.PORT = strdup(equal_ptr);
                equal_ptr = NULL;
                continue;
        };

Using strstr() incurs overhead when the string does not match because it
will traverse the entire line. strncmp() is a faster failure in this
case.

You will also have to manually free(comm_settings.PORT) at some point to
free the memory that strdup() has allocated.

Hope this helps.

Paul Braman
aeon@tampabay.rr.com



This archive was generated by hypermail 2.1.3 : Fri Aug 01 2014 - 19:24:29 EDT