开发者

fscanf matching one line, but not another, similar line

I'm attempting to read a file (particularly /proc/stat) to get data out of it. There are a multitude of ways to do this in C, but (so far) I'm using fscanf(). (However, I'm not particularly tied to it - it just seems to be well suited to what I want to do. If there's another, better way - please suggest it). The problem I'm seeing is that fscanf() will read the one line (with a particular format string), but refuses to glean any data if I change the format string to target a different line. Examples make this much clearer.

#include <stdio.h>
char *
get_cpu_perc() {
    unsigned long long cpu0_user=0;
    FILE* file = fopen("/proc/stat", "r");
    int fsf_ret;
    fsf_ret = fscanf(file, "cpu %llu", &cpu0_user);
    printf("%llu\n", cpu0_user);
    printf("%d\n", fsf_ret);
    return cpu0_user;
}
int
main(){
    get_cpu_perc();
    return 1;
}

The above works well - it selects the first number on the line starting with 'cpu '. I'd like to split this out into a per-core total - meanining I need to chage the fscanf() call to

fscanf(file, "cpu0 %llu", &cpu0_user);

However, I don't get any match on that line. It's probably obvious, but I'm extremely green when it comes to C. (Which isn't to say I'm unwilling to learn, but rather than I'm uninitiated into how this should really be done).

Since this really isn't a *nix specific problem, below is a few lines that replicate the behavior I see when I run this against a live /p开发者_开发百科roc/stat. You could save this and test against it, if you felt so inclined.

cpu  5885032 59114 1477054 15427556 39113 0 36078 0 0 0
cpu0 2888239 29861 682033 7814849 22952 0 24266 0 0 0
cpu1 2996792 29253 795020 7612706 16160 0 11812 0 0 0

My question is this: how do I get fscanf() to match against the second and third lines and not just the first? (This is possibly related to this question, but honestly - I'm not even doing anything so fancy nor messing with regex's here. Maybe I'm missing something?)


This should do it:

fscanf(file, "%*s %llu", &cpu0_user)

The %*s tells fscanf to read a string but not assign it to anything.


fscanf() doesn't search the input text. If the text at the beginning of the stream does not match the format, nothing is returned.

There are many approaches you could use here. One might be to use fgets() to get a line, look at the first few characters to determine which line it is, and then use fscanf() with the proper format.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜