Revised answer:
If you assume that there is no whitespace at the beginning of either attr or value (i.e., there is no space between the start of the line and the attr string, or the equal sign and the value string), then your program can be made to work with only a slight adjustment: change the multiple spaces in the second arguments to strstr() to single spaces. The revised code with a main() to demonstrate follows. If you wish to strip non-trailing whitespace, then, well, it's likely back to the debugger as you expand the problem or borrowing from the link in my original answer below.
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
/*
* attrvalue(): parse an attribute value pair.
*
* takes a string of the form "ATTRIBUTE = VALUE" and returns the atrribute name
* and value as seperate strings
*
*/
int
attrvalue(char *entry, char **attr, char **value)
{
char *copy;
char *p;
if (!entry || *entry == '\0')
return 1;
copy = strdup(entry);
*attr = strtok(copy, "=");
*value = strtok(NULL, "\n");
/* strip trailing whitespace from attr and value */
p = strstr(*attr, " ");
if(p)
*p = '\0';
p = strstr(*value, " ");
if(p)
*p = '\0';
return (0);
}
int main()
{
char *input = "asdf =blah "; // this works
//char *input = " asdf = blah"; // this would not
char *attr;
char *value;
attrvalue(input, &attr, &value);
printf("attr =\"%s\"", attr);
printf("value=\"%s\"", value);
return 0;
}
Original answer:
I'd use a different method of stripping out whitespace, as it's not even quite clear how strstr() would work as used in this situation. Here's the strstr() documentation, and here's a SO topic discussing the removal of whitespace in C.
Couple other thoughts:
if(p)
should be if(p != NULL)
, as a nit.
- What if second argument to strstr() is longer than the first?