Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sscanf delimiters for parsing?

Tags:

c

parsing

scanf

I am trying to parse the following string with sscanf:

query=testword&diskimg=simple.img

How can I use sscanf to parse out "testword" and "simple.img"? The delimiter arguments for sscanf really confuse me :/

Thank you!

like image 233
Jason Block Avatar asked Dec 07 '12 05:12

Jason Block


1 Answers

If you know that the length of "testword" will always be 8 characters, you can do it like this:

char str[] = "query=testword&diskimg=simple.img";
char buf1[100];
char buf2[100];

sscanf(str, "query=%8s&diskimg=%s", buf1, buf2);

buf1 will now contain "testword" and buf2 will contain "simple.img".

Alternatively, if you know that testword will always be preceded by = and followed by &, and that simple.img will always be preceded by =, you can use this:

sscanf(str, "%*[^=]%*c%[^&]%*[^=]%*c%s", buf1, buf2);

It's pretty cryptic, so here's the summary: each % designates the start of a chunk of text. If there's a * following the %, that means that we ignore that chunk and don't store it in one of our buffers. The ^ within the brackets means that this chunk contains any number of characters that are not the characters within the brackets (excepting ^ itself). %s reads a string of arbitrary length, and %c reads a single character.

So to sum up:

  • We keep reading and ignoring characters if they are not =.
  • We read and ignore another character (the equal sign).
  • Now we're at testword, so we keep reading and storing characters into buf1 until we encounter the & character.
  • More characters to read and ignore; we keep going until we hit = again.
  • We read and ignore a single character (again, the equal sign).
  • Finally, we store what's left ("simple.img") into buf2.
like image 92
dst2 Avatar answered Sep 27 '22 20:09

dst2