patterncMinor
Small function for getting character value
Viewed 0 times
functiongettingcharactervaluesmallfor
Problem
I want to extract some values in i-commas(") from lines like this:
Example:
where cp is a pointer the line above should return "9,0,1"
The function:
This code is ugly. Could anyone give me hints on how to write it better?
Example:
getCharVal ( cp, char "k=\"", 9)where cp is a pointer the line above should return "9,0,1"
The function:
#define ENDTAG "/>"
#define ICOMMAS '"'
char * getCharVal ( char *cp, char *att, size_t s)
{
char * val;
char * endTagP;
if (cp == NULL)return NULL;
cp = strstr(cp, att)+strlen(att);
if (cp == NULL) return NULL;
char * endP = strchr(cp, ICOMMAS);
if (endP == NULL) return NULL;
endTagP = strstr(cp, ENDTAG);
if (endTagP == NULL) return NULL;
if (endP > endTagP) return NULL;
size_t valsize = endP - cp ;
if (valsize > s) return NULL;
val = malloc(valsize + 1);
memcpy (val, cp, valsize);
val[valsize]='\0';
cp = endTagP;
return val;
}This code is ugly. Could anyone give me hints on how to write it better?
Solution
The easiest code to maintain is code that doesn't exist. For parsing XML, use an XML-parsing library, preferably with XPath support. Sometimes it might be justified to whip up your own code to extract values from XML, but it clearly does not make sense in this case. Not only is the code ugly by your own admission, low-level string- and memory-manipulation also distracts you from thinking about the big picture. Furthermore, your code will be less robust than a proper XML parser, and it will fail if the text is encoded in a semantically equivalent variant (for example, if a value is escaped).
Context
StackExchange Code Review Q#37684, answer score: 5
Revisions (0)
No revisions yet.