Currently working on developing parser using C. I wanted to extract portion of lines after a specific character set. For example, from following line "Target" need to be extracted.
"V { <Target> ;"
Now I use strstr() to locate lines contains "V { ", succeeded. but unable to remove "V { " portion to get clean target. usually strstr() supports sizeof() to make pointer beginning of "Target". But my code return nothing while using sizeof(). My code is below, thanks for your time.
while (fgets(line, MAX_LINE_LENGTH, textfile)){
const char *p1 = strstr(line, "V { "); // end of this line may include offset "+5", didn't work
const char *p2 = strstr(p1, ";"); // returns nothing using this code.
if (p1 != NULL){
size_t len = p2-p1;
char *res = (char*)malloc(sizeof(char)*(len+1));
strncpy(res, p1, len);
res[len] = '\0';
printf("%s\n", res);
}
}
p1 points to the start of the match.
Add an offset to p1 to get rid of what you do not need.
strncpy(res, p1+3, len-3);
res[len-3] = '\0';
(3 can be some other offset, depending on what you want).