Mercurial > hg > index.fcgi > rcg > rcg-1
changeset 4:99770a6b967d
rcg.c: use getopt.h and read in regex from arguments; use enum for exit codes
author | paulo@twcdns.fastsearch.net |
---|---|
date | Mon, 05 Apr 2010 23:45:38 -0700 |
parents | fe4b316b4386 |
children | 26e28ec5fe87 |
files | rcg.c |
diffstat | 1 files changed, 46 insertions(+), 6 deletions(-) [+] |
line diff
1.1 --- a/rcg.c Mon Apr 05 22:37:37 2010 -0700 1.2 +++ b/rcg.c Mon Apr 05 23:45:38 2010 -0700 1.3 @@ -5,11 +5,22 @@ 1.4 #define __USE_GNU 1.5 #include <string.h> 1.6 1.7 +#include <unistd.h> 1.8 + 1.9 +#define _GNU_SOURCE 1.10 +#include <getopt.h> 1.11 + 1.12 const size_t BUFSIZE = 5000; 1.13 1.14 const char *CLR_START = "-CLR_START-"; 1.15 const char *CLR_END = "-CLR_END-"; 1.16 1.17 +typedef enum _exit_code { 1.18 + EXIT_OK, 1.19 + EXIT_REALLOC_ERROR, 1.20 + EXIT_ARGS_ERROR, 1.21 +} Exit_code; 1.22 + 1.23 int re_error(int errcode, const regex_t *re) 1.24 { 1.25 char *err_string = calloc(BUFSIZE, sizeof(char)); 1.26 @@ -19,19 +30,49 @@ 1.27 return errcode; 1.28 } 1.29 1.30 -int realloc_error() 1.31 +Exit_code realloc_error() 1.32 { 1.33 fprintf(stderr, "realloc() failure \n"); 1.34 - return 1; 1.35 + return EXIT_REALLOC_ERROR; 1.36 +} 1.37 + 1.38 +Exit_code args_error() 1.39 +{ 1.40 + fprintf(stderr, "Invalid or nonexistent argument. \n"); 1.41 + return EXIT_ARGS_ERROR; 1.42 +} 1.43 + 1.44 +// returns regular expression argument 1.45 +char *parseArgs(int argc, char **argv) 1.46 +{ 1.47 + static struct option long_options[] = 1.48 + { 1.49 + { 0, 0, 0, 0 }, 1.50 + }; 1.51 + 1.52 + int c; 1.53 + int l; 1.54 + while ((c = getopt_long(argc, argv, "", long_options, &l)) >= 0) 1.55 + { 1.56 + } 1.57 + 1.58 + if (optind >= argc) 1.59 + exit(args_error()); 1.60 + 1.61 + return argv[optind]; 1.62 } 1.63 1.64 int main(int argc, char **argv) 1.65 { 1.66 + char *re_expression = parseArgs(argc, argv); 1.67 + 1.68 + fprintf(stderr, "re_expression = %s \n", re_expression); //d/ 20100405 PBA 1.69 + 1.70 char *buf = calloc(BUFSIZE, sizeof(char)); 1.71 1.72 int re_err; 1.73 regex_t *re = calloc(1, sizeof(regex_t)); 1.74 - re_err = regcomp(re, "Hello", REG_EXTENDED); 1.75 + re_err = regcomp(re, re_expression, REG_EXTENDED); 1.76 if (re_err != 0) 1.77 exit(re_error(re_err, re)); 1.78 1.79 @@ -40,7 +81,6 @@ 1.80 size_t CLR_START_len = strlen(CLR_START); 1.81 size_t CLR_END_len = strlen(CLR_END); 1.82 1.83 - 1.84 while (fgets(buf, BUFSIZE, stdin)) 1.85 { 1.86 int so = -1; 1.87 @@ -51,7 +91,7 @@ 1.88 unsigned int out_pos = 0; 1.89 unsigned int buf_pos = 0; 1.90 1.91 - while (re_err != REG_NOMATCH) 1.92 + for (re_err = 0; re_err != REG_NOMATCH;) 1.93 { 1.94 re_err = regexec(re, &buf[buf_pos], 1, rem, 0); 1.95 1.96 @@ -92,5 +132,5 @@ 1.97 free(out); 1.98 } 1.99 1.100 - return 0; 1.101 + return EXIT_OK; 1.102 }