int main(int argc, char** argv) { int repeat = 10; int max_n = 10; int trials = 1000000; if(argc > 0) { --argc; ++argv; } while(argc > 0) { if(argv[0][0] != '-') return usage(); else if(!handle_option(argc, argv, 'r', repeat) && !handle_option(argc, argv, 'n', max_n) && !handle_option(argc, argv, 't', trials)) { return usage(); } --argc; ++argv; } try { if(do_tests(repeat, max_n, trials)) { return 0; } else { return EXIT_FAILURE; } } catch(...) { std::cerr << boost::current_exception_diagnostic_information() << std::endl; return EXIT_FAILURE; } }
static int long_option(const struct weston_option *options, int count, char *arg) { int k, len; for (k = 0; k < count; k++) { if (!options[k].name) continue; len = strlen(options[k].name); if (strncmp(options[k].name, arg + 2, len) != 0) continue; if (options[k].type == WESTON_OPTION_BOOLEAN) { if (!arg[len + 2]) { * (int32_t *) options[k].data = 1; return 1; } } else if (arg[len+2] == '=') { return handle_option(options + k, arg + len + 3); } } return 0; }
static int short_option(const struct weston_option *options, int count, char *arg) { int k; if (!arg[1]) return 0; for (k = 0; k < count; k++) { if (options[k].short_name != arg[1]) continue; if (options[k].type == WESTON_OPTION_BOOLEAN) { if (!arg[2]) { * (int32_t *) options[k].data = 1; return 1; } } else if (arg[2]) { return handle_option(options + k, arg + 2); } else { return 0; } } return 0; }
/* Decode and handle the vector of command line options. LANG_MASK contains has a single bit set representing the current language. */ static void handle_options (unsigned int argc, const char **argv, unsigned int lang_mask) { unsigned int n, i; for (i = 1; i < argc; i += n) { const char *opt = argv[i]; /* Interpret "-" or a non-switch as a file name. */ if (opt[0] != '-' || opt[1] == '\0') { if (main_input_filename == NULL) main_input_filename = opt; add_input_filename (opt); n = 1; continue; } n = handle_option (argv + i, lang_mask); if (!n) { n = 1; error ("unrecognized command line option \"%s\"", opt); } } }
int main(int argc, char **argv) { int i,j; double ratio; #ifdef _WIN32 WORD wVersionRequested = MAKEWORD(2,2); WSADATA wsaData; (void) WSAStartup(wVersionRequested, &wsaData); #endif #ifndef _WIN32 if (signal(SIGPIPE, SIG_IGN) == SIG_ERR) return 1; #endif for (i = 1; i < argc; ++i) { for (j = 0; options[j].name; ++j) { if (!strcmp(argv[i],options[j].name)) { if (handle_option(argc,argv,&i,&options[j])<0) return 1; goto again; } } fprintf(stderr, "Unknown option '%s'\n", argv[i]); usage(); return 1; again: ; } if (cfg_help) { usage(); return 0; } cfg_tick.tv_sec = cfg_tick_msec / 1000; cfg_tick.tv_usec = (cfg_tick_msec % 1000)*1000; seconds_per_tick = ratio = cfg_tick_msec / 1000.0; cfg_connlimit *= ratio; cfg_grouplimit *= ratio; { struct timeval tv; evutil_gettimeofday(&tv, NULL); #ifdef _WIN32 srand(tv.tv_usec); #else srandom(tv.tv_usec); #endif } #ifndef EVENT__DISABLE_THREAD_SUPPORT evthread_enable_lock_debugging(); #endif return test_ratelimiting(); }
void update_motif(void) { motif_t * m = db->motifs; for (uint32_t i = 1; i < current_motif_index; i++) m = m->next; sprintf(current_motif_title, "%i/%i -- %s", (int)current_motif_index, (int)db->nb_motifs, m->name); current_motif_desc = m->desc; MULTIEDIT_SetText(motif_desc_widget, current_motif_desc); TEXT_SetText(motif_name_widget, current_motif_title); led_clear(); point_t * p = m->points; while (p != NULL) { led_set(p->x, p->y, p->z); p = p->next; } clear_points2blink(); option_t * o = m->options; while (o != NULL) { handle_option(o); o = o->next; } }
int main(int argc, char** argv) { int repeat = 1; int max_num_phases = BOOST_RANDOM_HYPEREXP_NUM_PHASES_MAX; double max_rate = BOOST_RANDOM_HYPEREXP_RATE_MAX; long long trials = BOOST_RANDOM_HYPEREXP_NUM_TRIALS; if (argc > 0) { --argc; ++argv; } while(argc > 0) { if (argv[0][0] != '-') { return usage(); } else if (!handle_option(argc, argv, "-r", repeat) && !handle_option(argc, argv, "-num_phases", max_num_phases) && !handle_option(argc, argv, "-rate", max_rate) && !handle_option(argc, argv, "-t", trials)) { return usage(); } --argc; ++argv; } try { if (do_tests(repeat, max_num_phases, max_rate, trials)) { return 0; } else { return EXIT_FAILURE; } } catch(...) { std::cerr << boost::current_exception_diagnostic_information() << std::endl; return EXIT_FAILURE; } }
/* * Handle parsing of default parameters. */ void fill_default_options(void *data, struct fio_option *options) { struct fio_option *o; dprint(FD_PARSE, "filling default options\n"); for (o = &options[0]; o->name; o++) if (o->def) handle_option(o, o->def, data); }
static size_t parse_args(arg_buf* args) { long r = frontend_syscall(SYS_getmainvars, va2pa(args), sizeof(*args), 0, 0, 0, 0, 0); kassert(r == 0); uint64_t* pk_argv = &args->buf[1]; // pk_argv[0] is the proxy kernel itself. skip it and any flags. size_t pk_argc = args->buf[0], arg = 1; for ( ; arg < pk_argc && *(char*)(uintptr_t)pk_argv[arg] == '-'; arg++) handle_option((const char*)(uintptr_t)pk_argv[arg]); for (size_t i = 0; arg + i < pk_argc; i++) args->argv[i] = (char*)(uintptr_t)pk_argv[arg + i]; return pk_argc - arg; }
static void parse_args(int argc, char* argv[]) { char* ptr; int ch; while((ch = getopt(argc, argv, "DNO:cn:qs:t:")) != -1) { switch(ch) { case 'c': opt_copymsg = 1; break; case 'n': opt_msglimit = strtoul(optarg, &ptr, 10); if(*ptr) usage("Invalid number for NUM."); break; case 'q': opt_quiet = 1; break; case 's': opt_subject_prefix = optarg; break; case 't': opt_timelimit = strtoul(optarg, &ptr, 10); if(*ptr) usage("Invalid number for TIME."); break; case 'D': opt_nodelete = 1; break; case 'N': opt_nosend = 1; break; case 'O': if ((ptr = strchr(optarg, '=')) == 0) handle_option(optarg, "1", 1); else { *ptr++ = 0; handle_option(optarg, ptr, strlen(ptr)); } break; default: usage(0); } } init_autoresponder(argc-optind, argv+optind); now = time(0); }
int parse_cmd_option(const char *opt, const char *val, struct fio_option *options, void *data) { struct fio_option *o; o = find_option(options, opt); if (!o) { fprintf(stderr, "Bad option <%s>\n", opt); return 1; } if (!handle_option(o, val, data)) return 0; fprintf(stderr, "fio: failed parsing %s=%s\n", opt, val); return 1; }
static int short_option_with_arg(const struct weston_option *options, int count, char *arg, char *param) { int k; if (!arg[1]) return 0; for (k = 0; k < count; k++) { if (options[k].short_name != arg[1]) continue; if (options[k].type == WESTON_OPTION_BOOLEAN) continue; return handle_option(options + k, param); } return 0; }
int parse_option(const char *opt, struct fio_option *options, void *data) { struct fio_option *o; char *post, *tmp; tmp = option_dup_subs(opt); o = get_option(tmp, options, &post); if (!o) { fprintf(stderr, "Bad option <%s>\n", tmp); free(tmp); return 1; } if (!handle_option(o, post, data)) { free(tmp); return 0; } fprintf(stderr, "fio: failed parsing %s\n", opt); free(tmp); return 1; }
/********************************************************************** * %FUNCTION: parse_config_file * %ARGUMENTS: * es -- event selector * fname -- filename to parse * %RETURNS: * -1 on error, 0 if all is OK * %DESCRIPTION: * Parses configuration file. ***********************************************************************/ int l2tp_parse_config_file(EventSelector *es, char const *fname) { char buf[512]; char name[512]; char value[512]; int r = 0; size_t l; char *line; FILE *fp; /* Defaults */ Settings.listen_port = 1701; Settings.listen_addr.s_addr = htonl(INADDR_ANY); fp = fopen(fname, "r"); if (!fp) { l2tp_set_errmsg("Could not open '%s' for reading: %s", fname, strerror(errno)); return -1; } /* Start in global context */ option_context_fn = NULL; while (fgets(buf, sizeof(buf), fp) != NULL) { l = strlen(buf); if (l && (buf[l] == '\n')) { buf[l--] = 0; } /* Skip leading whitespace */ line = buf; while(*line && isspace(*line)) line++; /* Ignore blank lines and comments */ if (!*line || *line == '#') { continue; } /* Split line into two words */ split_line_into_words(line, name, value); /* Check for context switch */ if (!strcasecmp(name, "global") || !strcasecmp(name, "section")) { r = parser_switch_context(es, name, value); if (r < 0) break; continue; } r = handle_option(es, name, value); if (r < 0) break; } fclose(fp); if (r >= 0) { if (option_context_fn) { r = option_context_fn(es, "*end*", "*end*"); option_context_fn = NULL; } } return r; }
int main(int argc, char **argv) { int i, j; int rc = 1; int options = 0; int errptr; const char *error; BOOL only_one_at_top; /* Process the options */ for (i = 1; i < argc; i++) { option_item *op = NULL; char *option_data = (char *)""; /* default to keep compiler happy */ BOOL longop; BOOL longopwasequals = FALSE; if (argv[i][0] != '-') break; /* If we hit an argument that is just "-", it may be a reference to STDIN, but only if we have previously had -f to define the patterns. */ if (argv[i][1] == 0) { if (pattern_filename != NULL) break; else exit(usage(2)); } /* Handle a long name option, or -- to terminate the options */ if (argv[i][1] == '-') { char *arg = argv[i] + 2; char *argequals = strchr(arg, '='); if (*arg == 0) /* -- terminates options */ { i++; break; /* out of the options-handling loop */ } longop = TRUE; /* Some long options have data that follows after =, for example file=name. Some options have variations in the long name spelling: specifically, we allow "regexp" because GNU grep allows it, though I personally go along with Jeff Friedl in preferring "regex" without the "p". These options are entered in the table as "regex(p)". No option is in both these categories, fortunately. */ for (op = optionlist; op->one_char != 0; op++) { char *opbra = strchr(op->long_name, '('); char *equals = strchr(op->long_name, '='); if (opbra == NULL) /* Not a (p) case */ { if (equals == NULL) /* Not thing=data case */ { if (strcmp(arg, op->long_name) == 0) break; } else /* Special case xxx=data */ { int oplen = equals - op->long_name; int arglen = (argequals == NULL)? strlen(arg) : argequals - arg; if (oplen == arglen && strncmp(arg, op->long_name, oplen) == 0) { option_data = arg + arglen; if (*option_data == '=') { option_data++; longopwasequals = TRUE; } break; } } } else /* Special case xxxx(p) */ { char buff1[24]; char buff2[24]; int baselen = opbra - op->long_name; sprintf(buff1, "%.*s", baselen, op->long_name); sprintf(buff2, "%s%.*s", buff1, strlen(op->long_name) - baselen - 2, opbra + 1); if (strcmp(arg, buff1) == 0 || strcmp(arg, buff2) == 0) break; } } if (op->one_char == 0) { fprintf(stderr, "pcregrep: Unknown option %s\n", argv[i]); exit(usage(2)); } } /* One-char options; many that have no data may be in a single argument; we continue till we hit the last one or one that needs data. */ else { char *s = argv[i] + 1; longop = FALSE; while (*s != 0) { for (op = optionlist; op->one_char != 0; op++) { if (*s == op->one_char) break; } if (op->one_char == 0) { fprintf(stderr, "pcregrep: Unknown option letter '%c' in \"%s\"\n", *s, argv[i]); exit(usage(2)); } if (op->type != OP_NODATA || s[1] == 0) { option_data = s+1; break; } options = handle_option(*s++, options); } } /* At this point we should have op pointing to a matched option */ if (op->type == OP_NODATA) options = handle_option(op->one_char, options); else { if (*option_data == 0) { if (i >= argc - 1 || longopwasequals) { fprintf(stderr, "pcregrep: Data missing after %s\n", argv[i]); exit(usage(2)); } option_data = argv[++i]; } if (op->type == OP_STRING) *((char **)op->dataptr) = option_data; else { char *endptr; int n = strtoul(option_data, &endptr, 10); if (*endptr != 0) { if (longop) fprintf(stderr, "pcregrep: Malformed number \"%s\" after --%s\n", option_data, op->long_name); else fprintf(stderr, "pcregrep: Malformed number \"%s\" after -%c\n", option_data, op->one_char); exit(usage(2)); } *((int *)op->dataptr) = n; } } } /* Options have been decoded. If -C was used, its value is used as a default for -A and -B. */ if (both_context > 0) { if (after_context == 0) after_context = both_context; if (before_context == 0) before_context = both_context; } pattern_list = (pcre **)malloc(MAX_PATTERN_COUNT * sizeof(pcre *)); hints_list = (pcre_extra **)malloc(MAX_PATTERN_COUNT * sizeof(pcre_extra *)); if (pattern_list == NULL || hints_list == NULL) { fprintf(stderr, "pcregrep: malloc failed\n"); return 2; } /* Compile the regular expression(s). */ if (pattern_filename != NULL) { FILE *f = fopen(pattern_filename, "r"); char buffer[MBUFTHIRD + 16]; char *rdstart; int adjust = 0; if (f == NULL) { fprintf(stderr, "pcregrep: Failed to open %s: %s\n", pattern_filename, strerror(errno)); return 2; } if (whole_lines) { strcpy(buffer, "^(?:"); adjust = 4; } else if (word_match) { strcpy(buffer, "\\b"); adjust = 2; } rdstart = buffer + adjust; while (fgets(rdstart, MBUFTHIRD, f) != NULL) { char *s = rdstart + (int)strlen(rdstart); if (pattern_count >= MAX_PATTERN_COUNT) { fprintf(stderr, "pcregrep: Too many patterns in file (max %d)\n", MAX_PATTERN_COUNT); return 2; } while (s > rdstart && isspace((unsigned char)(s[-1]))) s--; if (s == rdstart) continue; if (whole_lines) strcpy(s, ")$"); else if (word_match)strcpy(s, "\\b"); else *s = 0; pattern_list[pattern_count] = pcre_compile(buffer, options, &error, &errptr, NULL); if (pattern_list[pattern_count++] == NULL) { fprintf(stderr, "pcregrep: Error in regex number %d at offset %d: %s\n", pattern_count, errptr - adjust, error); return 2; } } fclose(f); } /* If no file name, a single regex must be given inline. */ else { char buffer[MBUFTHIRD + 16]; char *pat; int adjust = 0; if (i >= argc) return usage(2); if (whole_lines) { sprintf(buffer, "^(?:%.*s)$", MBUFTHIRD, argv[i++]); pat = buffer; adjust = 4; } else if (word_match) { sprintf(buffer, "\\b%.*s\\b", MBUFTHIRD, argv[i++]); pat = buffer; adjust = 2; } else pat = argv[i++]; pattern_list[0] = pcre_compile(pat, options, &error, &errptr, NULL); if (pattern_list[0] == NULL) { fprintf(stderr, "pcregrep: Error in regex at offset %d: %s\n", errptr - adjust, error); return 2; } pattern_count++; } /* Study the regular expressions, as we will be running them many times */ for (j = 0; j < pattern_count; j++) { hints_list[j] = pcre_study(pattern_list[j], 0, &error); if (error != NULL) { char s[16]; if (pattern_count == 1) s[0] = 0; else sprintf(s, " number %d", j); fprintf(stderr, "pcregrep: Error while studying regex%s: %s\n", s, error); return 2; } } /* If there are include or exclude patterns, compile them. */ if (exclude_pattern != NULL) { exclude_compiled = pcre_compile(exclude_pattern, 0, &error, &errptr, NULL); if (exclude_compiled == NULL) { fprintf(stderr, "pcregrep: Error in 'exclude' regex at offset %d: %s\n", errptr, error); return 2; } } if (include_pattern != NULL) { include_compiled = pcre_compile(include_pattern, 0, &error, &errptr, NULL); if (include_compiled == NULL) { fprintf(stderr, "pcregrep: Error in 'include' regex at offset %d: %s\n", errptr, error); return 2; } } /* If there are no further arguments, do the business on stdin and exit */ if (i >= argc) return pcregrep(stdin, (filenames_only || filenames_nomatch_only)? stdin_name : NULL); /* Otherwise, work through the remaining arguments as files or directories. Pass in the fact that there is only one argument at top level - this suppresses the file name if the argument is not a directory and filenames_only is not set. */ only_one_at_top = (i == argc - 1); for (; i < argc; i++) { int frc = grep_or_recurse(argv[i], recurse, filenames, only_one_at_top); if (frc > 1) rc = frc; else if (frc == 0 && rc == 1) rc = 0; } return rc; }
int main(int argc, char *argv[]) { // Set defaults set_defaults(); // Process cmdline Arguments for (int i = 1; i < argc; ++i) { if (!strcmp(argv[i],"--help")) { usage(); exit(0); } else if (!strncmp(argv[i],"--",2)) { if (!handle_option(argv[i])) { printf("Unrecognized option %s\n", argv[i]); usage(); exit(1); } } else { // Use as input file stream = fopen(argv[i], "r"); } } // Initialize the cache init_cache(); uint64_t totalRefs = 0; uint64_t totalPenalties = 0; uint32_t addr = 0; char i_or_d = '\0'; // Read each memory access from the trace while (read_mem_access(&addr, &i_or_d)) { totalRefs++; // Direct the memory access to the appropriate cache if (i_or_d == 'I') { totalPenalties += icache_access(addr); } else if (i_or_d == 'D') { totalPenalties += dcache_access(addr); } else { fprintf(stderr,"Input Error '%c' must be either 'I' or 'D'\n", i_or_d); exit(1); } } // Print out the statistics printStudentInfo(); printCacheConfig(); printCacheStats(); printf("Total Memory accesses: %16llu\n", totalRefs); printf("Total Memory penalties: %16llu\n", totalPenalties); if (totalRefs > 0) { printf("avg Memory access time: %16.2f cycles\n", (double)totalPenalties / totalRefs); } else { printf("avg Memory access time: -\n"); } // Cleanup fclose(stream); free(buf); return 0; }
void parse_rtsp(){ int str_len, cnt = 0; char *p, *q; char cmd[BUF_SIZE] = {0, }; if((str_len = read(rtsp_sock, cmd, BUF_SIZE)) > 0){ printf("-------------C -> S-------------\n" "%s\n", cmd); p = strtok(cmd, "\r\n"); if (strstr(p,"OPTIONS") != NULL){ rtspCmdType = RTSP_OPTIONS; p += 7; }else if (strstr(p,"DESCRIBE") != NULL){ rtspCmdType = RTSP_DESCRIBE; p += 9; }else if (strstr(p,"SETUP") != NULL) { rtspCmdType = RTSP_SETUP; p += 6; }else if (strstr(p,"PLAY") != NULL) { rtspCmdType = RTSP_PLAY; p += 5; }else if (strstr(p,"TEARDOWN") != NULL) { rtspCmdType = RTSP_TEARDOWN; p += 9; }else if(strstr(p, "PAUSE") != NULL){ rtspCmdType = RTSP_PAUSE; p += 6; }else{ printf("Command error\n"); close(rtsp_sock); exit(-1); } /* if(strstr(p, "rtsp://") != NULL && rtspCmdType == RTSP_OPTIONS) { p += 7; int i = 0; while(*p != '/') hostaddr[i++] = *(p++); hostaddr[i] = 0; i = 0; p++; while(*p != ' ') filename[i++] = *(p++); filename[i] = 0; } else { printf("URL error\n"); close(rtsp_sock); exit(-1); } */ hostaddr[0] = '1'; hostaddr[1] = '9'; hostaddr[2] = '2'; hostaddr[3] = '.'; hostaddr[4] = '1'; hostaddr[5] = '6'; hostaddr[6] = '8'; hostaddr[7] = '.'; hostaddr[8] = '5'; hostaddr[9] = '6'; hostaddr[10] = '.'; hostaddr[11] = '1'; hostaddr[12] = '0'; hostaddr[13] = '2'; hostaddr[14] = ':'; hostaddr[15] = '3'; hostaddr[16] = '0'; hostaddr[17] = '0'; hostaddr[18] = '5'; hostaddr[19] = '\0'; if(rtspCmdType == RTSP_OPTIONS) { char directive[32]; char host[256]; char version[32]; char file_name[32]; int pcnt; pcnt = sscanf(cmd, "%31s %255s %31s", directive, host, version); char *str_temp; str_temp = (char *) strrchr((char *)host, '/'); file_name[0] = '.'; file_name[1] = '.'; file_name[2] = '/'; file_name[3] = '.'; file_name[4] = '.'; file_name[5] = '/'; file_name[6] = 'm'; file_name[7] = 'e'; file_name[8] = 'd'; file_name[9] = 'i'; file_name[10] = 'a'; int i = 11; while(*str_temp != '\0') { file_name[i] = *(str_temp); if(i!=0) filename[i-12]= *(str_temp); i++; str_temp++; } file_name[i] = '\0'; filename[i-12]='\0'; inputStream = fopen(file_name, "rb"); } p = strtok(NULL, "\r\n"); if ((p = strstr(p, "CSeq")) != NULL) { p += 5; int i = 0; while(*p != 0) cseq[i++] = *(p++); cseq[i] = 0; } else { printf("CSeq error\n"); } if (rtspCmdType == RTSP_SETUP) { p = strtok(NULL, "\r\n"); p = strtok(NULL, "\r\n"); if ( strstr(p,"RTP/AVP/TCP") != NULL) transportMode = TCP; else transportMode = UDP; if((p = strstr(p, "client_port=")) != NULL){ p += 12; int i = 0; char port[25] = {0, }; while(*p != '-') port[i++] = *(p++); port[i] = 0; clientRTPPort = atoi(port); i = 0; p++; while(*p != 0){ if(*p != '\r' || *p != '\n') port[i++] = *(p++); } port[i] = 0; clientRTCPPort = atoi(port); } } } /* 이게 이제 진짜로 읽을려고 해서, 이 부분도 fork로 따로 들어줘야 할 거 같음, 아니면 무한루프돔여기서 if(streamer != NULL && streamer->rtcp_sock != 0) { while((str_len = read(streamer->rtcp_sock, cmd, BUF_SIZE)) > 0){ printf("rtcp : %s\n", cmd); } } */ switch(rtspCmdType){ case RTSP_OPTIONS : printf("option\n"); handle_option(); break; case RTSP_DESCRIBE : printf("describe\n"); handle_describe(); break; case RTSP_SETUP : printf("setup\n"); handle_setup(); break; case RTSP_PLAY : printf("play\n"); handle_play(); break; case RTSP_TEARDOWN : printf("teardown\n"); handle_teardown(); break; case RTSP_PAUSE : printf("pause\n"); handle_pause();break; default : printf("Not implemented\n"); return; } }
void parse_options(int * argc_p, char ** argv) { int i; const arg_opt_t *opt = NULL; char * tmp; int cmdind = 0; int optind = 0; for (i = 1; i < *argc_p; i++) { const char *arg = argv[i]; size_t len = strlen(arg); if (arg[0] == '-' && (arg[1] < '0' || arg[1] > '9')) { if (arg[1] == '-') { /* arg is a long option */ size_t name_len = len - 2; /* if arg is "--", there can be no more options */ if (len == 2) { optind = i + 1; if (cmdind == 0) { cmdind = optind; } break; } /* make sure we got an argument for the previous option */ if( opt && opt->argument) option_error(ERROR_MISSING_ARGUMENT, opt->longopt, opt->argument); /* retrieve a option argument */ char *value; if ((value = strchr(arg + 2, '=')) != NULL) { name_len = value - arg - 2; value++; } /* check if the option exists */ if ((opt=lookup_long_option(arg+2, name_len)) == NULL) { option_error(ERROR_UNKNOWN_OPTION, arg, NULL); } /* abort if we got an argument to the option and don't want one */ if( value && opt->argument == NULL) option_error(ERROR_GOT_ARGUMENT, arg, value); /* execute option callback */ if (value || opt->argument == NULL) { handle_option(opt->shortopt, value); opt = NULL; } } else { /* arg is a short option (or several) */ size_t j; if (len == 1) option_error(ERROR_UNKNOWN_OPTION, arg, NULL); for (j=1; j<len; j++) { /* make sure we got an argument for the previous option */ if (opt && opt->argument) option_error(ERROR_MISSING_ARGUMENT, opt->longopt, opt->argument); /* check if the option exists */ if ((opt = lookup_short_option(arg[j])) == NULL) option_error(ERROR_UNKNOWN_OPTION, arg, NULL); /* if no option argument is needed execute callback */ if (opt->argument == NULL) { handle_option(opt->shortopt, NULL); opt = NULL; } } } } else { /* No '-' */ if (opt && opt->argument) { /* arg is an option argument */ handle_option(opt->shortopt, arg); opt = NULL; } else { /* arg may the command; note it and read for more options */ if (cmdind == 0) cmdind = i; /* otherwise, it is the first command argument and we are done */ else { optind = i; break; } } } } if (optind == 0) optind = i; if (opt && opt->argument) option_error(ERROR_MISSING_ARGUMENT, opt->longopt, opt->argument); /* Parse the password from the host */ if (options.host != NULL && (tmp = strchr(options.host, '@')) != NULL) { size_t password_length = tmp - options.host; char *password = malloc(password_length + 1); memcpy(password, options.host, password_length); password[password_length] = 0; options.password = password; options.host = tmp + 1; } /* Convert port to an integer */ if (options.port_str) { options.port = strtol(options.port_str, &tmp, 10); if (options.port < 0 || *tmp != '\0') { fprintf(stderr, "Port \"%s\" is not a positive integer\n", options.port_str); exit(EXIT_FAILURE); } } if (options.format == NULL) { if ((options.format = getenv("MPC_FORMAT")) == NULL) options.format = F_DEFAULT; else options.custom_format = true; } /* Fix argv for command processing, which wants argv[1] to be the command, and so on. */ if (cmdind != 0) argv[1] = argv[cmdind]; if (optind > 1) { if ( optind == cmdind || cmdind == 0 ) { for (i = optind + 1; i < *argc_p; i++) argv[i-optind+2] = argv[i]; *argc_p -= optind - 1; } else { for (i = optind; i < *argc_p; i++) argv[i-optind+2] = argv[i]; *argc_p -= optind - 2; } } }
int main(int argc, char *argv[]) { // Parse args and set port number to use int port_num = -1; if (argc > 1) { for (int i = 1; i < argc; i++) { if (strncmp(argv[i], "-", 1) == 0) { if (handle_option(argv[i])) { return 1; } } else { port_num = atoi(argv[i]); } } } if (port_num == -1) { // Obtain http service struct servent *serv = getservbyname("http", "tcp"); // Does not require htons as getservbyname returns port number in network byte order (big endian) port_num = serv->s_port; endservent(); } printf("Initiating Web Server...\n\n"); struct sockaddr_in addr; // Create socket sock_listen = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if (sock_listen < 0) { printf("Failed to create listening socket\n"); return 1; } printf("Created socket with file descriptor: %d\n", sock_listen); // Setup signal handler to cleanup socket upon interrupt signal(SIGINT, cleanup_listening_socket); // Set socket options int opt_value = 1; if (setsockopt(sock_listen, SOL_SOCKET, SO_REUSEADDR, &opt_value, sizeof(opt_value)) == -1) { printf("Failed to set socket options\n"); close(sock_listen); return 1; } // Setup the address (port number) to bind to memset(&addr, 0, sizeof(addr)); addr.sin_family = AF_INET; addr.sin_port = port_num; addr.sin_addr.s_addr = INADDR_ANY; // Bind the socket to the address if (bind(sock_listen, (struct sockaddr *) &addr, sizeof(addr)) == 0) { printf("Successfully bound socket to port %d\n", ntohs(addr.sin_port)); // printf("Successfully bound socket to port %d (%d)\n", ntohs(addr.sin_port), addr.sin_port); } else { printf("Failed to bind socket to port %d: %s\n", ntohs(addr.sin_port), strerror(errno)); close(sock_listen); return 1; } // Listen on socket if (listen(sock_listen, BACKLOG) == 0) { printf("Listening on socket %d\n", sock_listen); // Get current hosting ip address FILE *ptr = popen(HOST_LOOKUP_CMD, "r"); if (ptr != NULL) { printf("Host(s): "); char buf[MAX_HOST_LEN]; char *success; do { memset(buf, 0, MAX_HOST_LEN); success = fgets(buf, MAX_HOST_LEN, ptr); if (buf != NULL) { printf("%s", buf); } } while(success != NULL); } } else { printf("Failed to listen on socket %d\n", sock_listen); close(sock_listen); return 1; } struct sockaddr client_address; socklen_t address_len; // Loop for accepting connections printf("Ready for client connections...\n"); while (1) { int sock_accept = accept(sock_listen, &client_address, &address_len); if (sock_accept == -1) { printf("Failed to accept connection on listening socket %d\n", sock_listen); } else { printf("Accepted new connection. Created socket with file descriptor: %d\n", sock_accept); pthread_t new_thread; struct thread_args *args = malloc(sizeof(struct thread_args)); args->socket_fd = sock_accept; if (pthread_create(&new_thread, NULL, listen_to_client, (void *) args)) { printf("Failed to create thread for connection with file descriptor: %d\n", sock_accept); } } } // Cleanup close(sock_listen); return 0; }
int bbus_parse_args(int argc, char** argv, const struct bbus_opt_list* optlist, struct bbus_nonopts** nonopts) { char* shortopts = NULL; struct option* longopts = NULL; const struct bbus_option* curopt = NULL; int opt; int ind = 0; int ret = BBUS_ARGS_GOOD; int flag; char* info = NULL; unsigned i; info = make_info_string(optlist); if (info == NULL) goto out_of_memory; shortopts = make_shortopts(optlist); if (shortopts == NULL) goto out_of_memory; longopts = make_longopts(optlist, &flag); if (longopts == NULL) goto out_of_memory; while ((opt = getopt_long(argc, argv, shortopts, longopts, &ind)) != -1) { switch (opt) { case '?': case ':': fprintf(stderr, "try %s --help\n", argv[0]); ret = BBUS_ARGS_ERR; goto out; break; case 0: /* Long option. */ if (flag < 0) { if (flag == OPT_VERSION) { fprintf(stdout, "%s %s\n", optlist->progname, optlist->version); } else { fprintf(stdout, "%s", info); } ret = BBUS_ARGS_HELP; goto out; } else { curopt = &optlist->opts[flag]; } break; default: /* * Short option. * * FIXME Probably should find a better way to find * the corresponding structure. */ for (i = 0; i < optlist->numopts; ++i) { if (optlist->opts[i].shortopt != 0) { if (optlist->opts[i].shortopt == opt) { curopt = &optlist->opts[i]; } } } break; } /* Now actually handle the option. */ handle_option(curopt->action, curopt->actdata, optarg); } for (i = 0; i < optlist->numpargs; ++i) { if (optind >= argc) { fprintf(stderr, "%s: expected additional parameters" "\ntry %s --help\n", argv[0], argv[0]); ret = BBUS_ARGS_ERR; goto out; } handle_option(optlist->pargs[i].action, optlist->pargs[i].actdata, argv[optind]); ++optind; } if (nonopts != NULL) { *nonopts = find_nonopts(argc, argv); if (*nonopts == NULL) goto out_of_memory; } goto out; out_of_memory: fprintf(stderr, "%s: %s\n", __FUNCTION__, bbus_strerror(BBUS_ENOMEM)); ret = BBUS_ARGS_ERR; out: bbus_free(shortopts); bbus_free(longopts); bbus_free(info); return ret; }
/** @brief Execute option parser * * @param argc argument count (from main) * @param argv argument vector (from main) * * @return number of arguments remaining */ int optparse_exec(int argc, char *argv[]) { int i; #ifdef OPTPARSE_DEBUG printf("%s:%d: argc = %d, argv[0] = '%s'\n", __FILE__, __LINE__, argc, argv[0]); #endif /* check --help and --version */ if (argc == 2) { if (strcmp(argv[1], "--help") == 0) { #ifdef OPTPARSE_DEBUG printf("%s:%d: got --help\n", __FILE__, __LINE__); #endif optparse_help(); return OPT_EXIT_HELP; } else if (strcmp(argv[1], "--version") == 0) { #ifdef OPTPARSE_DEBUG printf("%s:%d: got --version\n", __FILE__, __LINE__); #endif optparse_version(); return OPT_EXIT_VERSION; } } /* parse argument list */ for (i = 1; i < argc; i++) { const char *arg = argv[i]; int delta; if (arg[0] != '-') { /* not an option */ #ifdef OPTPARSE_DEBUG printf("%s:%d: found argument: '%s'\n", __FILE__, __LINE__, arg); #endif if (!arglist_add_arg(arg)) { return OPT_EXIT_ERROR; } } else { option_decl_t *opt; #ifdef OPTPARSE_DEBUG printf("%s:%d: found possible option: '%s'\n", __FILE__, __LINE__, arg); #endif if (arg[1] == '-') { /* long option */ opt = find_option(0, arg + 2); } else { opt = find_option(arg[1], NULL); } if (opt == NULL) { fprintf(stderr, "%s: unknown option '%s', continuing\n", prg_name, arg); /* don't just complain, do something (thanks iAN) */ return OPT_EXIT_ERROR; } delta = handle_option(opt, argv[i + 1]); if (delta < 0) { return OPT_EXIT_ERROR; } i += delta; } } return (int)arglist_used; }
/******************************************************************** * Parse command-line option (global) * * Parameters: * cfg_file: TRUE if called from a configuration file * FALSE if command-line option * * Returns: * -1: parameter was found (opt doesn't start with -+) * 0: option was found * 1: option was NOT found * 2: an error ********************************************************************/ static int parse_cmd_opt(char *opt, BOOL cfg_file) { option_item *op; int opt_off; char *p_err; if(opt == NULL) { /* internal error */ DM_ERR_ASSERT("opt == NULL\n"); return 0; } /* Process the options */ /* Parameters */ if (!(*opt == '-' || *opt == '+')) return -1; if (OPL("-0") || OPL("--e0-file")) { /* before-execution log messages filename */ if(opt_off > 2 && *(opt + opt_off) == '=') /* long option, ignore '=' */ opt_off++; f_close(opts.e0_fname, &opts.e0_file); opts.e0_fname = opt + opt_off; if(strcmp(opts.e0_fname, "-") == 0) /* standard output */ opts.e0_fname = NULL; f_open(opts.e0_fname, &opts.e0_file); return 0; } if (OPL("-1") || OPL("--e1-file")) { /* after-execution log messages filename */ if(opt_off > 2 && *(opt + opt_off) == '=') /* long option, ignore '=' */ opt_off++; f_close(opts.e1_fname, &opts.e1_file); opts.e1_fname = opt + opt_off; if(strcmp(opts.e1_fname, "-") == 0) /* standard output */ opts.e1_fname = NULL; f_open(opts.e1_fname, &opts.e1_file); return 0; } if (OPL("-2") || OPL("--e2-file")) { /* after-evaluation log messages filename */ if(opt_off > 2 && *(opt + opt_off) == '=') /* long option, ignore '=' */ opt_off++; f_close(opts.e2_fname, &opts.e2_file); opts.e2_fname = opt + opt_off; if(strcmp(opts.e2_fname, "-") == 0) /* standard output */ opts.e2_fname = NULL; f_open(opts.e2_fname, &opts.e2_file); return 0; } if (OPL("-a") || OPL("--ansi")) { /* ANSI colors */ if(opt_off > 2 && *(opt + opt_off) == '=') /* long option, ignore '=' */ opt_off++; opts.ansi = strtol(opt + opt_off, &p_err, 0); if (p_err == opt + opt_off || *p_err) { /* no option value given || value contains invalid/non-digit char */ opts.ansi = TRUE; } DM_ANSI_SET(opts.ansi); return 0; } if (OPL("-b") || OPL("--verbose")) { /* verbose/quiet execution */ if(opt_off > 2 && *(opt + opt_off) == '=') /* long option, ignore '=' */ opt_off++; opts.verbose = strtol(opt + opt_off, &p_err, 0); if (p_err == opt + opt_off || *p_err) /* no option value given || value contains invalid/non-digit char */ opts.verbose = 1; /* limit verbosity */ if(opts.verbose > VERBOSE_MAX) opts.verbose = VERBOSE_MAX; else if(opts.verbose < VERBOSE_MIN) opts.verbose = VERBOSE_MIN; if(opts.verbose > 0) DM_LOG_SET_L((1 << opts.verbose) - 1); if(opts.verbose <= -1) /* disable warning messages */ DM_WARN_SET_L(0); if(opts.verbose <= -2) /* disable error messages */ DM_ERR_SET_L(0); return 0; } if (OPL("-h") || OPL("-?") || OPL("--help")) { /* help */ if(opt_off > 2 && *(opt + opt_off) == '=') /* long option, ignore '=' */ opt_off++; opts.help = strtol(opt + opt_off, &p_err, 0); if (p_err == opt + opt_off || *p_err) { /* no option value given || value contains invalid/non-digit char */ opts.help = 0; } // hlp(opts.help); exit(0); hlp(0); /* only level 0 help so far */ exit(0); return 0; } if (OPL("-d") || OPL("--dbg-file")) { /* debug messages output filename */ if(opt_off > 2 && *(opt + opt_off) == '=') /* long option, ignore '=' */ opt_off++; opts.dbg_fname = opt + opt_off; DM_DBG_OPEN(opts.dbg_fname); /* old stream is automatically closed */ return 0; } if (OPL("-e") || OPL("--eval")) { /* default evaluation threshold for branches */ if(opt_off > 2 && *(opt + opt_off) == '=') /* long option, ignore '=' */ opt_off++; opts.s2_eval = strtol(opt + opt_off, &p_err, 0); if (p_err == opt + opt_off || *p_err) /* no option value given || value contains invalid/non-digit char */ opts.s2_eval = S2_EVAL; return 0; } if (OPL("-f") || OPL("--file")) { /* script filename */ if(opt_off > 2 && *(opt + opt_off) == '=') /* long option, ignore '=' */ opt_off++; opts.scr_fname = opt + opt_off; if(strcmp(opts.scr_fname, "-") == 0) /* standard input */ opts.scr_fname = NULL; return 0; } if (OPL("-g") || OPL("--progress")) { /* progress bar */ if(opt_off > 2 && *(opt + opt_off) == '=') /* long option, ignore '=' */ opt_off++; opts.progress_bar = strtol(opt + opt_off, &p_err, 0); if (p_err == opt + opt_off || *p_err) /* no option value given || value contains invalid/non-digit char */ opts.progress_bar = TRUE; return 0; } if (OPL("-i") || OPL("--pp-indent")) { /* pretty-printer indentation value */ BOOL vrb_msg = FALSE; if(opt_off > 2 && *(opt + opt_off) == '=') /* long option, ignore '=' */ opt_off++; opts.pp_indent = strtol(opt + opt_off, &p_err, 0); /* limit pretty-printer indentation */ if (opts.pp_indent > PP_INDENT_MAX) { opts.pp_indent = PP_INDENT_MAX; vrb_msg = TRUE; } else if (opts.pp_indent < PP_INDENT_MIN) { opts.pp_indent = PP_INDENT_MIN; vrb_msg = TRUE; } if (p_err == opt + opt_off || *p_err || opts.pp_indent < PP_INDENT_MIN || opts.pp_indent > PP_INDENT_MAX) { /* no option value given || value contains invalid/non-digit char */ opts.pp_indent = PP_INDENT; vrb_msg = TRUE; } if(vrb_msg) DM_DBG(DM_N(1),_("pretty-printer indentation set to %d spaces\n"), opts.pp_indent); return 0; } if (OPL("-l") || OPL("--log-file")) { /* default log filename */ if(opt_off > 2 && *(opt + opt_off) == '=') /* long option, ignore '=' */ opt_off++; opts.log_fname = opt + opt_off; DM_LOG_OPEN(opts.log_fname); /* old stream is automatically closed */ return 0; } if (OPL("-p") || OPL("--pp-out-file")) { /* pretty-printer output file */ if(opt_off > 2 && *(opt + opt_off) == '=') /* long option, ignore '=' */ opt_off++; f_close(opts.pp_fname, &opts.pp_file); opts.pp_fname = opt + opt_off; if(strcmp(opts.pp_fname, "-") == 0) /* standard output */ opts.pp_fname = NULL; f_open(opts.pp_fname, &opts.pp_file); return 0; } if (OPL("-r") || OPL("--err-file")) { /* error messages output filename */ if(opt_off > 2 && *(opt + opt_off) == '=') /* long option, ignore '=' */ opt_off++; opts.err_fname = opt + opt_off; DM_ERR_OPEN(opts.err_fname); /* old stream is automatically closed */ return 0; } if (OPL("-s") || OPL("--show-defaults")) { /* show default values (pretty-printer, evaluator) ON/OFF */ if(opt_off > 2 && *(opt + opt_off) == '=') /* long option, ignore '=' */ opt_off++; opts.show_defaults = strtol(opt + opt_off, &p_err, 0); if (p_err == opt + opt_off || *p_err) { /* no option value given || value contains invalid/non-digit char */ opts.show_defaults = TRUE; } return 0; } if (OPL("-S") || OPL("--simple-name")) { opts.simple_name = TRUE; } if (OPL("-T") || OPL("--threads")) { /* threads in the thread pool */ if(opt_off > 2 && *(opt + opt_off) == '=') /* long option, ignore '=' */ opt_off++; opts.tp_size = strtol(opt + opt_off, &p_err, 0); if (p_err == opt + opt_off || *p_err) /* no option value given || value contains invalid/non-digit char */ opts.tp_size = TP_THREADS_DEF; /* limit verbosity */ if(opts.tp_size > TP_THREADS_MAX) opts.tp_size = TP_THREADS_MAX; else if(opts.tp_size < TP_THREADS_MIN) opts.tp_size = TP_THREADS_MIN; return 0; } if (OPL("-t") || OPL("--timeout")) { /* default timeout for branches */ if(opt_off > 2 && *(opt + opt_off) == '=') /* long option, ignore '=' */ opt_off++; opts.s2_timeout = strtol(opt + opt_off, &p_err, 0); if (p_err == opt + opt_off || *p_err) /* no option value given || value contains invalid/non-digit char */ opts.s2_timeout = S2_TIMEOUT; return 0; } if (OPL("-V") || OPL("--version")) { /* print the version and exit */ fprintf(stderr,_("%s version %s\n"), PNAME(), VERSION); exit(ERR_OK); } if (OPL("-w") || OPL("--warn-file")) { /* warning messages output filename */ if(opt_off > 2 && *(opt + opt_off) == '=') /* long option, ignore '=' */ opt_off++; opts.warn_fname = opt + opt_off; DM_WARN_OPEN(opts.warn_fname); /* old stream is automatically closed */ return 0; } /* default option handling */ if (opt[1] == '-' || opt[1] == '+') { int ret_val = 1; /* try long options */ for (op = optionlist; op->short_name; op++) { if (op->long_name && strcmp(opt+2, op->long_name) == 0) { ret_val = 0; handle_option(op->short_name); break; } } return ret_val; } else /* try short options */ return handle_option(opt+1); return 1; }
int main(int argc, char **argv) { int n; int stoparg = 0; char *fname1 = NULL, *fname2 = NULL; FILE *fpin = stdin, *fpout = stdout; char *s; /* Some CP/M and DOS compilers don't support argv[0] */ if (argv[0][0]) cnv_progname = argv[0]; /* Argument parsing */ for (n = 1; n < argc; n++) if (isarg(argv[n]) && !stoparg) { if (!strcmp(argv[n], "--")) { stoparg = 1; continue; } /* Check for likely help commands */ if (!stricmp(argv[n], "--help")) help(); if (!stricmp(argv[n]+1, "h" )) help(); #ifdef __MSDOS__ if (!stricmp(argv[n]+1, "?" )) help(); #endif #ifdef CPM if (!stricmp(argv[n]+1, "?" )) help(); if (!stricmp(argv[n], "//" )) help(); if (!stricmp(argv[n], "[help]")) help(); if (!stricmp(argv[n], "[h]" )) help(); #endif /* OK, it isn't a help command. */ if (argv[n][0] == '-' && argv[n][1] == '-') { handle_option(1, argv[n]+2); continue; } /* CP/M-style [VARIABLE=VALUE,VARIABLE=VALUE] options */ #ifdef CPM if (argv[n][0] == '[') { char *s; do { s = handle_option(1, argv[n]+2); } while ( s && (*s) && (*s != ']')); continue; } #endif /* Short option */ handle_option(0, argv[n]+1); } else { if (!fname1) fname1 = argv[n]; else if (!fname2) fname2 = argv[n]; else { fprintf(stderr, "%s: This program takes two filenames, so '%s' is ignored.\n", cnv_progname, argv[n]); } } /* Options parsed */ if (fname1) { fpin = fopen(fname1, "rb"); if (!fpin) { perror(fname1); exit(1); } } else fname1 = "<stdin>"; if (fname2) { fpout = fopen(fname2, "w+b"); if (!fpout) { fclose(fpin); perror(fname2); exit(1); } } else fname2 = "<stdout>"; s = cnv_execute(fpin, fpout); if (fpin != stdin) fclose(fpin); if (fpout != stdout) fclose(fpout); if (!s) return 0; if (fpout != stdout) remove(fname2); fprintf(stderr, "%s: %s\n", cnv_progname, s); return 1; }
int read_dump(const char *filename, db_base **dbs, char *md5, int md5_len) { char *p; int ret = -1, retlen = 0; int kv=0; bool md5sum = false; pki_base *pki = NULL; db_base *db; QFile file; QString line; file.setFileName(filename); if (! file.open(QIODevice::ReadOnly)) { throw errorEx(filename, strerror(errno)); return -1; } for (;;) { line = readLine(&file); //printf("Line: '%s'\n", CCHAR(line)); if (line.isNull()) { ret = 0; break; } //printf("FIRST char = '%c'\n", CCHAR(line)[0]); if (line[0] == ' ') { if (database >= 0 && database < 5) db = dbs[database]; else db = NULL; kv ^= 1; p = read_data(CCHAR(line.trimmed()), &retlen); if (db && !md5) { if (kv) { pki = db->newPKI(); if (!pki) { break; } pki->setIntName(p); } else { try { pki->oldFromData((unsigned char*)p, retlen); db->insert(pki); } catch (errorEx &err) { printf("Error catched for '%s'\n", CCHAR(pki->getIntName())); } } } else if (md5) { if (database == 5) { p = read_data(CCHAR(line.trimmed()), &retlen); if (kv) md5sum = (!strcmp(p, "pwhash")) ? true : false; if (!kv && md5sum) { strncpy(md5, p, md5_len); ret = 0; break; } } } free(p); } else { if (kv) { printf("Binary value expected\n"); break; } handle_option(line); } } file.close(); if (ret <0) { throw errorEx(filename, strerror(errno)); return -1; } return 0; }
int main(int argc, char **argv) { int i, j; int rc = 1; int options = 0; int errptr; const char *error; BOOL only_one_at_top; /* Process the options */ for (i = 1; i < argc; i++) { if (argv[i][0] != '-') break; /* Missing options */ if (argv[i][1] == 0) exit(usage(2)); /* Long name options */ if (argv[i][1] == '-') { option_item *op; if (strncmp(argv[i]+2, "file=", 5) == 0) { pattern_filename = argv[i] + 7; continue; } for (op = optionlist; op->one_char != 0; op++) { if (strcmp(argv[i]+2, op->long_name) == 0) { options = handle_option(op->one_char, options); break; } } if (op->one_char == 0) { fprintf(stderr, "pcregrep: Unknown option %s\n", argv[i]); exit(usage(2)); } } /* One-char options */ else { char *s = argv[i] + 1; while (*s != 0) { if (*s == 'f') { pattern_filename = s + 1; if (pattern_filename[0] == 0) { if (i >= argc - 1) { fprintf(stderr, "pcregrep: File name missing after -f\n"); exit(usage(2)); } pattern_filename = argv[++i]; } break; } else options = handle_option(*s++, options); } } } pattern_list = malloc(MAX_PATTERN_COUNT * sizeof(pcre *)); hints_list = malloc(MAX_PATTERN_COUNT * sizeof(pcre_extra *)); if (pattern_list == NULL || hints_list == NULL) { fprintf(stderr, "pcregrep: malloc failed\n"); return 2; } /* Compile the regular expression(s). */ if (pattern_filename != NULL) { FILE *f = fopen(pattern_filename, "r"); char buffer[BUFSIZ]; if (f == NULL) { fprintf(stderr, "pcregrep: Failed to open %s: %s\n", pattern_filename, strerror(errno)); return 2; } while (fgets(buffer, sizeof(buffer), f) != NULL) { char *s = buffer + (int)strlen(buffer); if (pattern_count >= MAX_PATTERN_COUNT) { fprintf(stderr, "pcregrep: Too many patterns in file (max %d)\n", MAX_PATTERN_COUNT); return 2; } while (s > buffer && isspace((unsigned char)(s[-1]))) s--; if (s == buffer) continue; *s = 0; pattern_list[pattern_count] = pcre_compile(buffer, options, &error, &errptr, NULL); if (pattern_list[pattern_count++] == NULL) { fprintf(stderr, "pcregrep: Error in regex number %d at offset %d: %s\n", pattern_count, errptr, error); return 2; } } fclose(f); } /* If no file name, a single regex must be given inline */ else { if (i >= argc) return usage(2); pattern_list[0] = pcre_compile(argv[i++], options, &error, &errptr, NULL); if (pattern_list[0] == NULL) { fprintf(stderr, "pcregrep: Error in regex at offset %d: %s\n", errptr, error); return 2; } pattern_count++; } /* Study the regular expressions, as we will be running them may times */ for (j = 0; j < pattern_count; j++) { hints_list[j] = pcre_study(pattern_list[j], 0, &error); if (error != NULL) { char s[16]; if (pattern_count == 1) s[0] = 0; else sprintf(s, " number %d", j); fprintf(stderr, "pcregrep: Error while studying regex%s: %s\n", s, error); return 2; } } /* If there are no further arguments, do the business on stdin and exit */ if (i >= argc) return pcregrep(stdin, NULL); /* Otherwise, work through the remaining arguments as files or directories. Pass in the fact that there is only one argument at top level - this suppresses the file name if the argument is not a directory. */ only_one_at_top = (i == argc - 1); if (filenames_only) filenames = TRUE; for (; i < argc; i++) { int frc = grep_or_recurse(argv[i], recurse, filenames, only_one_at_top); if (frc == 0 && rc == 1) rc = 0; } return rc; }