Lev Walkin | c9b2f28 | 2017-11-05 20:32:15 -0800 | [diff] [blame] | 1 | /* |
| 2 | * Since working awk is not present on every supported platform |
| 3 | * (notably Solaris), and nawk is not the same on Solaris and Linux, |
| 4 | * this program is a replacement for it to extract test parameter from the. |
| 5 | * string specified in the command line. |
| 6 | */ |
| 7 | #include <stdio.h> |
| 8 | #include <stdlib.h> |
| 9 | #include <string.h> |
| 10 | #include <sysexits.h> |
| 11 | |
| 12 | static void |
| 13 | usage(const char *progname) { |
| 14 | fprintf(stderr, "Search PARAM=VALUE pattern in the given string\n"); |
| 15 | fprintf(stderr, "Usage: %s <parameter-name> <default-value> <string>\n", |
| 16 | progname); |
| 17 | } |
| 18 | |
| 19 | static const char * |
| 20 | search(const char *param, const char *haystack) { |
| 21 | |
| 22 | const char *p = strstr(haystack, param); |
| 23 | if(p && p[strlen(param)] == '=') { |
| 24 | const char *param_begin = &p[strlen(param) + 1]; |
| 25 | const char *param_end = param_begin; |
| 26 | for(param_end = param_begin; param_end; param_end++) { |
| 27 | switch(*param_end) { |
| 28 | case '0' ... '9': |
| 29 | continue; |
| 30 | default: |
| 31 | break; |
| 32 | } |
| 33 | break; |
| 34 | } |
| 35 | |
| 36 | static char static_buf[64]; |
| 37 | |
| 38 | if((param_end - param_begin) <= 0) { |
| 39 | fprintf(stderr, "Parameter %s is malformed after '='\n", param); |
| 40 | return NULL; |
| 41 | } |
| 42 | |
| 43 | if((param_end - param_begin) >= (ssize_t)sizeof(static_buf)) { |
| 44 | fprintf(stderr, "Parameter %s value exceeds buffer size %zu\n", |
| 45 | param, sizeof(static_buf)); |
| 46 | return NULL; |
| 47 | } |
| 48 | |
| 49 | memcpy(static_buf, param_begin, param_end - param_begin); |
| 50 | static_buf[param_end - param_begin] = '\0'; |
| 51 | return static_buf; |
| 52 | } else if(p) { |
| 53 | fprintf(stderr, "Parameter %s should contain '='\n", param); |
| 54 | return NULL; |
| 55 | } |
| 56 | |
| 57 | return NULL; |
| 58 | } |
| 59 | |
| 60 | int |
| 61 | main(int ac, char **av) { |
| 62 | if(ac != 4) { |
| 63 | usage(av[0]); |
| 64 | exit(EX_USAGE); |
| 65 | } |
| 66 | |
| 67 | const char *value = search(av[1], av[3]); |
| 68 | if(value) { |
| 69 | printf("%s\n", value); |
| 70 | } else { |
| 71 | printf("%s\n", av[2]); |
| 72 | } |
| 73 | } |