C 语言正则表达式与mmap结合使用
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <string.h>
#include <errno.h>
#include <regex.h>
char *mptr = MAP_FAILED;
int main()
{
int status = 0;
//FILE *fp = NULL;
int cflags = REG_EXTENDED;
regmatch_t pmatch[4];
const size_t nmatch = 4;
char *buf = NULL;;
regex_t reg;
const char *pattern = "^[ \t]*trapsink[ \t]*([0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3})[ \t]*([A-Za-z_0-9-]*)?[ \t]*([0-9]*)?";
//这里的表达式与标准的似乎有点不同。
#if 0
char buf[1024];
fp = fopen("snmpd.conf", "r");
if (fp == NULL)
{
return -1;
}
#endif
int fsize = load_snmpd_file();
buf = mptr;
regcomp(®, pattern, cflags);
while(buf < mptr + fsize)
{
if (!regexec(®, buf, nmatch, pmatch,0))
{
printf("\n\n");
printf("so:%seo:%s\n", buf+pmatch[0].rm_so, buf+pmatch[0].rm_eo);
printf("so:%seo:%s\n", buf+pmatch[1].rm_so, buf+pmatch[1].rm_eo);
printf("so:%seo:%s\n", buf+pmatch[2].rm_so, buf+pmatch[2].rm_eo);
printf("so:%seo:%s\n", buf+pmatch[3].rm_so, buf+pmatch[3].rm_eo);
}
buf = strchr(buf, '\n');
while(buf && *buf == '\n') buf++;
}
#if 0
if (fp != NULL)
{
fclose(fp);
}
#endif
munmap(mptr, fsize);
regfree(®);
return 0;
}
int load_snmpd_file()
{
int fd = -1;
fd = open("snmpd.conf", O_RDWR);//打开方式与下面的PROT_READ|PROT_WRITE有关。
if (fd == -1)
{
return -errno;
}
int fsize = lseek(fd, 0, SEEK_END) - lseek(fd, 0, SEEK_SET);//要定位到文件开头。
mptr = mmap(NULL, fsize, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0);
if (mptr == MAP_FAILED)
{
return -errno;
}
close(fd);//可以先关闭文件。
return fsize;
}
自己写的测试代码。学一点,收获一点。学到的都是自己的!
浙公网安备 33010602011771号