简体   繁体   中英

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:00.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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM