Reputation: 41
The string I am trying to parse is called str1, and it contains PRETTY_NAME="Ubuntu 20.04.1 LTS"
The goal is to have one variable contain PRETTY_NAME
, and the other contains Ubuntu 20.04.1 LTS
. I have declared both variables as char *var1, *var2
This has to be done with the sscanf function in C.
My current code looks like: sscanf(str1, "%s[^=]^s", var1. var2);
The output I am receiving is that both var1, and var2 return (null)
.
What am I doing wrong?
Upvotes: 0
Views: 355
Reputation: 945
the %s
matches the entire string terminates at white space or \0
including =
in that case, you can't use that here, and you haven't initialized any of your char buffer with a size which leads to crash or undefined behavior. here is a simplified parser.
void parse(const char* str, char* pretty, char* release) {
int pretty_end, start, end;
sscanf(str, "%*[^=]%n=\"%n%*[^\"]%n\"", &pretty_end, &start, &end);
strncpy(pretty, str, pretty_end);
pretty[pretty_end] = '\0';
strncpy(release, str+start, end-start);
release[end - start] = '\0';
}
int main() {
const char* str = "PRETTY_NAME=\"Ubuntu 20.04.1 LTS\"";
char pretty[256];
char release[256];
parse(str, pretty, release);
return 0;
}
Upvotes: 1