通过sscanf解析syslog消息

时间:2012-04-19 07:13:29

标签: c syslog scanf

我收到了syslog条消息

<14>2012-04-19T03:54:18+08:00.527800 server3000 status: 00|00|The average CPU, memory, disk usage and total network flow are 5.0%, 5.0%, 5.0% and 5 bytes respectively for the last hour.\n

如何通过函数2012-04-19,03:54:18+08:00.527800,server3000,status,00,00 and 5.0获取单词sscanf

#include <stdio.h>
#include <stdlib.h>

int main(void) {
int t1,t2 = 0;
char programname[20], deviceip[16], date[11], time[9];
char logmsg[30];
const char * s = "<14>2012-04-19T03:54:18.527800+08:00 server3000 status: 00|00|The average CPU, memory, disk usage and total network flow are 5.0%, 5.0%, 5.0% and 5 bytes respectively for the last hour";
sscanf(s, "<%*d>%[^T]T%[^.].%*[^ ] %[^ ] %[^:]: %d|%d|%[^\n]", date, time,deviceip, programname, &t1, &t2, logmsg);
return 0;
}

1 个答案:

答案 0 :(得分:0)

您可能希望保存sscanf的结果并检查其值:

int rc = sscanf(...);
if(rc < 7)
    // failed to match or extract
代码中的

sscanf返回7,表示您的格式字符串匹配并提取了所有7个参数。