soap
soap

Reputation: 1068

C scanf formatting

While reading one of the stackoverflow code, I came across following code snippet. This snippet is reading from a /proc/pid_of_process/stat file.

 47     if (fscanf(fpstat, "%*d %*s %*c %*d %*d %*d %*d %*d %*u %*u %*u %*u %*u %lu"
 48                 "%lu %ld %ld %*d %*d %*d %*d %*u %lu %ld",
 49                 &result->utime_ticks, &result->stime_ticks,
 50                 &result->cutime_ticks, &result->cstime_ticks, &result->vsize,
 51                 &rss) == EOF) {
 52         fclose(fpstat);
 53         return -1;
 54     }

I tried it and this code works. My question is basic C format specifier, how is it working as there are only 5 variables absorbing the values whereas the format specifiers are clearly much more than that. Which variable gets mapped to which format specifier here ?

Following is one sample output from /proc/pid_of_process/stat file.

[13:13 abc@europa ~] > cat /proc/27320/stat
27320 (a.out) R 13904 27320 13904 34835 27320 4218880 195 0 0 0 31145 0 0 0 20 0 1 0 85427028     4304896 92 18446744073709551615 4194304 4196252 140734857124320 140734857122088 4195763 0 0 0 0 0 0 0     17 7 0 0 0 0 0 6295056 6295624 21291008 140734857127361 140734857127369 140734857127369 140734857129968 0

Upvotes: 1

Views: 385

Answers (3)

Roland Illig
Roland Illig

Reputation: 41625

The * apparently means read but discard. See http://pubs.opengroup.org/onlinepubs/009695399/functions/fscanf.html

By the way, it is an error if fscanf(…) != 6. Whether it returns EOF doesn't matter in this case.

Upvotes: 2

Leeor
Leeor

Reputation: 19706

See - http://www.cplusplus.com/reference/cstdio/scanf/

The asterisk marks:

An optional starting asterisk indicates that the data is to be read from the stream but ignored (i.e. it is not stored in the location pointed by an argument).

By the way, I count 6 variables, and 6 non-ignored format specifiers

if (fscanf(fpstat, "%*d %*s %*c %*d %*d %*d %*d %*d %*u %*u %*u %*u %*u %lu"
"%lu %ld %ld %*d %*d %*d %*d %*u %lu %ld",

Upvotes: 1

Random832
Random832

Reputation: 39000

The ones with an asterisk in them don't store the value in an argument.

Upvotes: 2

Related Questions