(1)fscanf sscanf
FILE *in = fopen ("/proc/uptime", "r");
long uptim = 0, a, b;
if (in)
{
if (2 == fscanf (in, "%ld.%ld", &a, &b))
uptim = a * 100 + b;
fclose (in);
}
------------------------------------------------------------------------------------------------------------------------------
file = fopen("/proc/stat", "r");
if (file == 0)
{
printf("file:/proc/stat not exist/n");
return ;
}
char line[512];
// 获取相关数据
while (line == fgets(line, 512, file))
{
if (4 == sscanf(line, "cpu %lu %lu %lu %lu", &cpuInfo.CpuUser,&cpuInfo.CpuNice,
&cpuInfo.CpuSystem,&cpuInfo.CpuIdel))
{
break;
}
}
(2)strtok 与strtok_
我们有一段字符串 "Fred male 25,John male 62,Anna female 16" 我们希望把这个字符串整理输入到一个struct,
char [25] name ;
char [6] sex;
char [4] age;
}
#include<string.h>
#define INFO_MAX_SZ 255
int main()
{
int in=0;
char buffer[INFO_MAX_SZ]="Fred male 25,John male 62,Anna female 16";
char *p[20];
char *buf=buffer;
while((p[in]=strtok(buf,","))!=NULL) {
buf=p[in];
while((p[in]=strtok(buf," "))!=NULL) {
in++;
buf=NULL;
}
p[in++]="***"; //表现分割
buf=NULL; }
printf("Here we have %d strings/n",i);
for (int j=0; j<in; j++)
printf(">%s</n",p[j]);
return 0;
}
Here we have 4 strings
>Fred<
>male<
>25<
>***<
这只是一小段的数据,并不是我们需要的。但这是为什么呢? 这是因为strtok使用一个static(静态)指针来操作数据,让我来分析一下以上代码的运行过程:
红色为strtok的 内置指针指向的位置, 蓝色为strtok对字符串的 修改
1. " Fred male 25,John male 62,Anna female 16" //外循环
2. "Fred male 25 /0 John male 62,Anna female 16" //进入内循环
3. "Fred /0 male 25/0John male 62,Anna female 16"
4. "Fred/0male /0 25/0John male 62,Anna female 16"
5 "Fred/0male/025 /0John male 62,Anna female 16" //内循环遇到"/0"回到外循环
6 "Fred/0male/025 /0John male 62,Anna female 16" //外循环遇到"/0"运行结束。
3. 使用strtok_r
在这种情况我们应该使用strtok_r, strtok reentrant.
char *strtok_r(char *s, const char *delim, char **ptrptr);
相对strtok我们需要为strtok提供一个指针来操作,而不是像strtok使用配套的指针。
代码:
#include<string.h>
#define INFO_MAX_SZ 255
int main()
{
int in=0;
char buffer[INFO_MAX_SZ]="Fred male 25,John male 62,Anna female 16";
char *p[20];
char *buf=buffer;
char *outer_ptr=NULL;
char *inner_ptr=NULL;
while((p[in]=strtok_r(buf,",",&outer_ptr))!=NULL) {
buf=p[in];
while((p[in]=strtok_r(buf," ",&inner_ptr))!=NULL) {
in++;
buf=NULL;
}
p[in++]="***";
buf=NULL; }
printf("Here we have %d strings/n",i);
for (int j=0; jn<i; j++)
printf(">%s</n",p[j]);
return 0;
}
这一次的输出为:
Here we have 12 strings
>Fred<
>male<
>25<
>***<
>John<
>male<
>62<
>***<
>Anna<
>female<
>16<
>***<
让我来分析一下以上代码的运行过程:
红色为strtok_r的outer_ptr指向的位置,
绿色为strtok_r的inner_ptr指向的位置,
蓝色为strtok对字符串的修改
1. "Fred male 25,John male 62,Anna female 16" //外循环
2. "Fred male 25/0John male 62,Anna female 16"//进入内循环
3. "Fred/0male 25/0John male 62,Anna female 16"
4 "Fred/0male/025/0John male 62,Anna female 16"
5 "Fred/0male/025/0John male 62,Anna female 16" //内循环遇到"/0"回到外循环
6 "Fred/0male/025/0John male 62/0Anna female 16"//进入内循环