view rcg.c @ 3:fe4b316b4386

rcg.c: working multiple regexec matches; couple of error handling functions
author paulo@twcdns.fastsearch.net
date Mon, 05 Apr 2010 22:37:37 -0700
parents 4efb50ce4c9c
children 99770a6b967d
line source
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <regex.h>
5 #define __USE_GNU
6 #include <string.h>
8 const size_t BUFSIZE = 5000;
10 const char *CLR_START = "-CLR_START-";
11 const char *CLR_END = "-CLR_END-";
13 int re_error(int errcode, const regex_t *re)
14 {
15 char *err_string = calloc(BUFSIZE, sizeof(char));
16 regerror(errcode, re, err_string, BUFSIZE*sizeof(char));
17 fprintf(stderr, "%s \n", err_string);
18 free(err_string);
19 return errcode;
20 }
22 int realloc_error()
23 {
24 fprintf(stderr, "realloc() failure \n");
25 return 1;
26 }
28 int main(int argc, char **argv)
29 {
30 char *buf = calloc(BUFSIZE, sizeof(char));
32 int re_err;
33 regex_t *re = calloc(1, sizeof(regex_t));
34 re_err = regcomp(re, "Hello", REG_EXTENDED);
35 if (re_err != 0)
36 exit(re_error(re_err, re));
38 regmatch_t *rem = calloc(1, sizeof(regmatch_t));
40 size_t CLR_START_len = strlen(CLR_START);
41 size_t CLR_END_len = strlen(CLR_END);
44 while (fgets(buf, BUFSIZE, stdin))
45 {
46 int so = -1;
47 int eo = -1;
49 size_t out_len = strlen(buf);
50 char *out = calloc(out_len, sizeof(char));
51 unsigned int out_pos = 0;
52 unsigned int buf_pos = 0;
54 while (re_err != REG_NOMATCH)
55 {
56 re_err = regexec(re, &buf[buf_pos], 1, rem, 0);
58 //fprintf(stderr, "%s", &buf[buf_pos]); //d// 20100405 PBA
60 if (out_len >= (BUFSIZE - buf_pos))
61 out_len = (BUFSIZE - buf_pos) - 1;
63 so = rem[0].rm_so;
64 eo = rem[0].rm_eo;
66 //fprintf(stderr, "%d %d \n", so, eo); //d// 20100327 PBA
68 if (re_err != REG_NOMATCH && so >= 0 && eo >= 0)
69 {
70 int match_len = eo - so;
71 out_len += CLR_START_len + CLR_END_len;
72 out = (char *)realloc(out, out_len*sizeof(char));
73 if (!out)
74 exit(realloc_error());
75 strncpy(&out[out_pos], &buf[buf_pos], so);
76 out_pos += so;
77 buf_pos += so;
78 strncpy(&out[out_pos], CLR_START, CLR_START_len);
79 out_pos += CLR_START_len;
80 strncpy(&out[out_pos], &buf[buf_pos], match_len);
81 out_pos += match_len;
82 strncpy(&out[out_pos], CLR_END, CLR_END_len);
83 out_pos += CLR_END_len;
85 buf_pos += match_len;
86 }
87 else
88 strncpy(&out[out_pos], &buf[buf_pos], out_len - out_pos);
89 }
91 fputs(out, stdout);
92 free(out);
93 }
95 return 0;
96 }