开发者

sscanf: get first and last token in a string

Is it possible by using sscanf to get the first token then skip some tokens and then get the last one?

For example, the output of /bin/ps -fu1000

  cm  2249  1548   0   0:00.00 ttys001    0:开发者_StackOverflow00.01 man sscanf

I have tried:

sscanf(line, "%s %[^\n]", user, cmd);

The result should be:

user = "cm";
cmd = "man sscanf":

But it does not work.


Yes, but it's ugly and can't be error checked properly.

/* assuming `user` and `cmd` are character arrays defined with 42 bytes */
if (sscanf(line, "%41s%*s%*s%*s%*s%*s%*s %41[^\n]", user, cmd) != 2) {
    /* handle error */
} else {
    /* hopefully ok */
}

You can replace some of the %*s with %*d. The * means that the item is parsed but not assigned anywhere (it is ignored).

In the statement, there are 6 ignored items corresponding to the items between "cm" and "man sscanf" in your example.

Also note I limited the input to 41 characters in the scanf itself. Make sure you do not write outside the objects.


EDIT: I added a space before the last conversion because, unlike %s or %d conversions, the %[ conversion does not skip leading whitespace.


Perhaps you'd better look at strtok

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜