sscanf解析符合一定模式的字符串或者文件内容

 1     char * pszLog = "192.168.110.98 - - 1264348800 "GET http://www.xxxxxxx.cc/web/validate/captcha.php?cid=134&3307 HTTP/1.0" 404 534 "-" "Trend Micro WTP Add-On 1.2.1046" TCP_MISS:FIRST_UP_PARENT 13";
 2 
 3     char szIP[16] = {0};
 4     char szTime[16] = {0};
 5     char szURL[256] = {0};
 6     char szCmd[8]   = {0};
 7     int  nStatus;
 8     int  nCode;
 9     char szProfile[64] = {0};
10     char szProtocol[64] = {0};
11     int  nRetCode;
12     char szBuf[32] = {0};
13     sscanf(pszLog, "%s - - %s %*["]%s %1000[^"]" %d %d %*["]%1000[^"]" %*["]%1000[^"]" %s %d
", 
14                     szIP, szTime, szCmd, szURL, &nStatus, &nCode, szProfile, szProtocol, szBuf, &nRetCode);
15 
16     printf("szIP:[%s]
", szIP);
17     printf("szTime:[%s]
", szTime);
18     printf("szCmd:[%s]
", szCmd);
19     printf("szURL:[%s]
", szURL);
20     printf("nStatus:[%d]
", nStatus);
21     printf("nCode:[%d]
", nCode);
22     printf("szProfile:[%s]
", szProfile);
23     printf("szProtocol:[%s]
", szProtocol);
24     printf("nRetCode:[%d]
", nRetCode);
25     printf("szBuf:[%s]
", szBuf);

说明:
第一个格式 %s,将提取串中的IP地址
第二个格式 - - ,将跳过/匹配串中的“ - - ”
第三个格式 %*["],将跳过一个引号“"”
第四个格式 %s, 将提出串中的GET
第五个格式 %1000[^"]",将提取1000个字符(包含空格)直到引号“"”,但是不包含引号,否则sccanf遇到空格停止提取
第六个格式:%d
第七个格式:%d,这个两个格式将提取串中的数字
第八个格式:%*["],将跳过引号
第九个格式:%1000[^"]",将提取串中的"-"符号,然后跳过引号
第十个格式:%*["],将跳过引号
第十一个格式:%1000[^"]",将提出串中的profile
第十二个格式:%s,将提取最后一个串
第十三个格式:%d,将提取最后一个数字

2. 解析无线路由器信息,AP名字中包含空格

//bc:05:43:ea:fa:5b       2412    -49     [WPA2-PSK-CCMP][WPS][ESS]       TPLINK 7270

格式串:"%s %*d %d %s %64[^
]"
第一个格式:%s,将提取BSSID值
第二个格式:%*d,将跳过带宽值,2.4G
第三个格式:%d,将提取信号值
第四个格式:%s,将提取安全认证信息
第五个格式:%64[^ ],将提取路由器的名称直到遇到换行符号。

3. 解析特定格式串

ssid="TEST_AP"
/* %*[^=], skip "ssid"
   * ="   , skip "=""
   * %[^"], get the remain string except the quota.
*/
格式串 "%*[^=]="%[^"]"
第一个格式串:%*[^=],将跳过ssid
第二个格式串:=",将匹配串中的等号和左引号
第三个格式串:%[^"],将匹配TEST_AP这个名字
原文地址:https://www.cnblogs.com/eric-geoffrey/p/4762781.html