sscanf无法匹配字符串

sscanf无法匹配字符串,c,C,我只是在做一个非常简单的sscanf,它失败了,我不知道为什么(我是C的初学者) 我相信它应该会起作用,我为此而发疯 下面是代码示例: int rval; // return value char* buf; char* file = "/proc/stat"; long unsigned int intr=0, introld=0; buf=file2buf(file); if((rval=sscanf(buf, "intr %lu", &

我只是在做一个非常简单的sscanf,它失败了,我不知道为什么(我是C的初学者)

我相信它应该会起作用,我为此而发疯

下面是代码示例:

int rval; // return value
char* buf;
    
char* file = "/proc/stat";

long unsigned int intr=0, introld=0;

buf=file2buf(file);
if((rval=sscanf(buf, "intr %lu", &introld)) < 1) perror("ERROR");
printf("buffer: %s\nintrold: %lu\n", buf, introld);
free(buf);
int-rval;//返回值
char*buf;
char*file=“/proc/stat”;
长无符号整数intr=0,introld=0;
buf=file2buf(文件);
if((rval=sscanf(buf,“intr%lu”和introld))<1)perror(“错误”);
printf(“缓冲区:%s\n控制区:%lu\n”,buf,introld);
免费(buf);
下面是它打印出来的内容:

错误:成功

缓冲区:cpu 1226442 3373 193292 19167181 57056 3 154 0 0

cpu0 323691 790 47844 4778847 9693 0 62 0 0 0

cpu1 290857 1430 42436 4804284 20607 0 25 0 0 0

cpu2 326087 608 57761 4763973 10862 240 0 0

cpu3 285805 544 45249 4820075 15893 0 25 0 0

intr 48727278 36 26655 0 0 0 0 0 0 0 0 0 1 11277 0 3788861 0 0 0 0 0 70288 0 0 0 0 0 0 0 0 33 0 443731 0 25936 1429307 25 893 2807619

简介:0


显然,匹配字符串(intr)就在那里。我犯了什么明显的错误?

问题是你的缓冲区。它包含“
cpu…”。。。诸如此类的废话。
要使sscanf工作,缓冲区必须仅以
intr
开头

或者-正如其他注释中所建议的那样-必须修剪在
sscanf
函数中传递的字符串,以便提取
intr
后面的字符串,并仅将其传递给sscanf。(即没有cpu+额外的废话-也没有intr)尝试简单地将数字(包含数字的字符串)传递到
sccanf
,而不强制它进行字符匹配

您可以使用
p=strstrstr(buf,“intr”)
,然后使用
sscanf(p+5,“&lu”…)
。p+5将跳过“intr”的字符。

不进行常规模式匹配,它会尝试精确匹配输入,这意味着传递给
sscanf
的字符串必须以
intr>开头
以使其能够匹配

您应考虑从文件逐行读取,并尝试使用例如“代码> STRNCMP < /代码>进行匹配,然后在匹配行上调用<代码> SCANFF < /代码>。或者查找一个正则表达式库。

<代码> sSCANF(BUF, > >代码> sSCANF(STRSTR(BUF,ITEN)),这是相同的(见C11,67.2 PAR 2)。