1. sscanf函数
sscanf是C标准库函数,用于从字符串中读取格式化输入。
头文件:
#include <stdio.h>
函数原型如下:
int sscanf(const char *s, const char *format, ...);
函数返回值:返回成功读取的数量。
2. 使用实例
AT指令参考文章:
提取信号强度
AT命令返回结果为:
+CSQ: 17,0
OK
先使用strstr找到标志字符:
str = strstr(buffer, "+CSQ");
if (!str) {
return -1;
}
接着使用sscanf提取数值类型:
ret = sscanf(str, "+CSQ:%d,%d", &rssi, &ber);
if (ret != 2) {
return -1;
}
提取基站信息
AT命令返回结果为:
+CREG: 2,0,"252A","6DD2104",7
OK
使用sscanf提取固定长度字符:
sscanf(buffer, "+CREG:%d,%d,\"%4s\",\"%7s\"", &n, &stat, lac_buf, ci_buf);
提取IP地址
AT命令返回结果为:
+CIFSR:STAIP,"10.89.100.53"
+CIFSR:STAMAC,"dc:29:19:bb:d7:d3"
OK
使用sscanf提取数值类型:
sscanf(str + strlen("STAIP,"), "\"%d.%d.%d.%d\"", &seg1, &seg2, &seg3, &seg4);
另外一种写法是直接写到格式化字符串中:
sscanf(str, "STAIP,\"%d.%d.%d.%d\"", &seg1, &seg2, &seg3, &seg4);
提取MAC地址
AT命令返回结果为:
+CIFSR:STAIP,"10.89.100.53"
+CIFSR:STAMAC,"dc:29:19:bb:d7:d3"
OK
使用sscanf提取十六进制数值类型:
sscanf(str + strlen("STAMAC,"), "\"%2x:%2x:%2x:%2x:%2x:%2x\"", &seg1, &seg2, &seg3, &seg4,&seg5,&seg6);
正则表达式提取不定长字符
AT命令返回结果为:
+CWLAP:(4,"TP-LINK_PocketAP_DFBCD4",-57,"38:83:45:df:bc:d4",6)
+CWLAP:(3,"LSTM",-61,"8c:21:0a:bc:8e:70",13)
+CWLAP:(3,"LabWiFi",-62,"68:3b:78:8f:16:23",1)
+CWLAP:(0,"GuestWiFi",-64,"68:3b:78:8f:16:22",1)
OK
先找到+CWLAP :
strstr(buffer+offset, "+CWLAP:");
使用sscanf+正则表达式提取ssid、mac、rssi:
sscanf(str+strlen("+CWLAP:"), "(%d,\"%[^\"]\",%d,\"%[^\"]\",", &ecn, ssid, &rssi, mac);
读取之后,将str指针移动到该行结束,进行下一轮的查找:
while (*str++ != '\n') {
offset++;
}
接收更多精彩文章及资源推送,欢迎订阅我的微信公众号:『mculover666』。
|