void json_object_start(char **ptr, const char *fieldname) { unsigned int indents = strcount(*ptr, "{") + strcount(*ptr, "[") - (strcount(*ptr, "]") + strcount(*ptr, "}")); json_start_member(ptr, fieldname); if (indents) { tal_append_fmt(ptr, "\n"); while (indents--) tal_append_fmt(ptr, "\t"); } tal_append_fmt(ptr, "{ "); }
/* We might need more ../ for nested modules. */ static const char *link_prefix(struct manifest *m) { char *prefix = tal_strdup(m, "../../"); unsigned int i; for (i = 0; i < strcount(m->modname, "/"); i++) prefix = tal_strcat(m, take(prefix), "../"); return tal_strcat(m, take(prefix), "licenses/"); }
int xstrtoken(char strg[], int pos, int len, int dp, char *tokens[], int xkey) { if ((xkey >= strcount(tokens)) || (xkey < 0)) { buffer[0] = 0; } else { sprintf(buffer,strfmt(len,dp,'s'),tokens[xkey]); } return xstr_____s(strg,pos,len,buffer); }
int main() { std::string input; std::cout << "Wprowadz wiersz:"; getline(std::cin, input); while (std::cin) { if (input.length() == 0) break; strcount(input); std::cout << "Wprowadz wiersz:"; getline(std::cin, input); } std::cout << "Koniec" << std::endl; return 0; }
int main(void) { int size; int size_gene; size_gene = sizeof(gene); size = sizeof(gene); printf("%s\n", gene); count(gene,size); printf("\n"); strcount(gene); list_main(); return 0; }
char * build_part_choices(struct partition *parts[], const int part_count) { char *list[part_count]; char *tmp, *tmp2; int i, max_len, len; //printf("part_count=%d\n", part_count); if (part_count <= 0) return NULL; max_len = 0; for (i = 0; i < part_count; i++) { len = strlen(parts[i]->description) - strcount(parts[i]->description, ','); if (len > max_len) max_len = len; } // pad with spaces for (i = 0; i < part_count; i++) { asprintf(&list[i], "%-*s", max_len, parts[i]->description); } max_len = strlen("n/a"); for (i = 0; i < part_count; i++) { if (parts[i]->size > 0 && strlen(size_desc(parts[i]->size)) > max_len) max_len = strlen(size_desc(parts[i]->size)); } // add and pad for (i = 0; i < part_count; i++) { asprintf(&tmp, "%s %-*s", list[i], max_len, (parts[i]->size > 0) ? size_desc(parts[i]->size) : "n/a"); free(list[i]); list[i] = tmp; } max_len = strlen("n/a"); for (i = 0; i < part_count; i++) { if (parts[i]->op.filesystem != NULL) { if (strlen(parts[i]->op.filesystem) > max_len) max_len = strlen(parts[i]->op.filesystem); } else if (parts[i]->fstype != NULL && strlen(parts[i]->fstype) > max_len) max_len = strlen(parts[i]->fstype); } for (i = 0; i < part_count; i++) { asprintf(&tmp, "%s %-*s", list[i], max_len, (parts[i]->op.filesystem != NULL) ? parts[i]->op.filesystem : (parts[i]->fstype != NULL) ? parts[i]->fstype : "n/a"); free(list[i]); list[i] = tmp; } max_len = 0; for (i = 0; i < part_count; i++) { if (parts[i]->op.mountpoint != NULL && strlen(parts[i]->op.mountpoint) > max_len) max_len = strlen(parts[i]->op.mountpoint); } if (max_len > 0) for (i = 0; i < part_count; i++) { asprintf(&tmp, "%s %-*s", list[i], max_len, (parts[i]->op.mountpoint != NULL) ? parts[i]->op.mountpoint : ""); free(list[i]); list[i] = tmp; } /* PHEW */ tmp = list[0]; //printf("<%s>\n", list[0]); for (i = 1; i < part_count; i++) { //printf("<%s>\n", list[i]); asprintf(&tmp2, "%s, %s", tmp, list[i]); free(list[i]); free(tmp); tmp = tmp2; } return tmp; }
/* Simple test code to create a gateway transaction */ int main(int argc, char *argv[]) { int fd, i, off; const char *method; char *cmd, *resp, *idstr, *rpc_filename; char *result_end; struct sockaddr_un addr; jsmntok_t *toks; const jsmntok_t *result, *error, *id; char *pettycoin_dir; const tal_t *ctx = tal(NULL, char); size_t num_opens, num_closes; bool valid; err_set_progname(argv[0]); opt_set_alloc(opt_allocfn, tal_reallocfn, tal_freefn); pettycoin_dir_register_opts(ctx, &pettycoin_dir, &rpc_filename); opt_register_noarg("--help|-h", opt_usage_and_exit, "<command> [<params>...]", "Show this message"); opt_register_noarg("--version|-V", opt_version_and_exit, VERSION, "Display version and exit"); opt_early_parse(argc, argv, opt_log_stderr_exit); opt_parse(&argc, argv, opt_log_stderr_exit); method = argv[1]; if (!method) errx(ERROR_USAGE, "Need at least one argument\n%s", opt_usage(argv[0], NULL)); if (chdir(pettycoin_dir) != 0) err(ERROR_TALKING_TO_PETTYCOIN, "Moving into '%s'", pettycoin_dir); fd = socket(AF_UNIX, SOCK_STREAM, 0); if (strlen(rpc_filename) + 1 > sizeof(addr.sun_path)) errx(ERROR_USAGE, "rpc filename '%s' too long", rpc_filename); strcpy(addr.sun_path, rpc_filename); addr.sun_family = AF_UNIX; if (connect(fd, (struct sockaddr *)&addr, sizeof(addr)) != 0) err(ERROR_TALKING_TO_PETTYCOIN, "Connecting to '%s'", rpc_filename); idstr = tal_fmt(ctx, "pettycoin_query-%i", getpid()); cmd = tal_fmt(ctx, "{ \"method\" : \"%s\", \"id\" : \"%s\", \"params\" : [ ", method, idstr); for (i = 2; i < argc; i++) { /* Numbers are left unquoted, and quoted things left alone. */ if (strspn(argv[i], "0123456789") == strlen(argv[i]) || argv[i][0] == '"') tal_append_fmt(&cmd, "%s", argv[i]); else tal_append_fmt(&cmd, "\"%s\"", argv[i]); if (i != argc - 1) tal_append_fmt(&cmd, ", "); } tal_append_fmt(&cmd, "] }"); if (!write_all(fd, cmd, strlen(cmd))) err(ERROR_TALKING_TO_PETTYCOIN, "Writing command"); resp = tal_arr(cmd, char, 100); off = 0; num_opens = num_closes = 0; while ((i = read(fd, resp + off, tal_count(resp) - 1 - off)) > 0) { resp[off + i] = '\0'; num_opens += strcount(resp + off, "{"); num_closes += strcount(resp + off, "}"); off += i; if (off == tal_count(resp) - 1) tal_resize(&resp, tal_count(resp) * 2); /* parsing huge outputs is slow: do quick check first. */ if (num_opens == num_closes && strstr(resp, "\"result\"")) break; } if (i < 0) err(ERROR_TALKING_TO_PETTYCOIN, "reading response"); /* Parsing huge results is too slow, so hack fastpath common case */ result_end = tal_fmt(ctx, ", \"error\" : null, \"id\" : \"%s\" }\n", idstr); if (strstarts(resp, "{ \"result\" : ") && strends(resp, result_end)) { /* Result is OK, so dump it */ resp += strlen("{ \"result\" : "); printf("%.*s\n", (int)(strlen(resp) - strlen(result_end)), resp); tal_free(ctx); return 0; } toks = json_parse_input(resp, off, &valid); if (!toks || !valid) errx(ERROR_TALKING_TO_PETTYCOIN, "Malformed response '%s'", resp); result = json_get_member(resp, toks, "result"); if (!result) errx(ERROR_TALKING_TO_PETTYCOIN, "Missing 'result' in response '%s'", resp); error = json_get_member(resp, toks, "error"); if (!error) errx(ERROR_TALKING_TO_PETTYCOIN, "Missing 'error' in response '%s'", resp); id = json_get_member(resp, toks, "id"); if (!id) errx(ERROR_TALKING_TO_PETTYCOIN, "Missing 'id' in response '%s'", resp); if (!json_tok_streq(resp, id, idstr)) errx(ERROR_TALKING_TO_PETTYCOIN, "Incorrect 'id' in response: %.*s", json_tok_len(id), json_tok_contents(resp, id)); if (json_tok_is_null(resp, error)) { printf("%.*s\n", json_tok_len(result), json_tok_contents(resp, result)); tal_free(ctx); return 0; } printf("%.*s\n", json_tok_len(error), json_tok_contents(resp, error)); tal_free(ctx); return 1; }
/* * Parse the configuration file at `path' and execute the `action' call-back * functions for any directives defined by the array of config options (first * argument). * * For unknown directives that are encountered, you can optionally pass a * call-back function for the third argument to be called for unknowns. * * Returns zero on success; otherwise returns -1 and errno should be consulted. */ int parse_config(struct fp_config options[], const char *path, int (*unknown)(struct fp_config *option, uint32_t line, char *directive, char *value), uint16_t processing_options) { uint8_t bequals; uint8_t bsemicolon; uint8_t case_sensitive; uint8_t comment = 0; uint8_t end; uint8_t found; uint8_t have_equals = 0; uint8_t quote; uint8_t require_equals; uint8_t strict_equals; char p[2]; char *directive; char *t; char *value; int error; int fd; ssize_t r = 1; uint32_t dsize; uint32_t line = 1; uint32_t n; uint32_t vsize; uint32_t x; off_t charpos; off_t curpos; char rpath[PATH_MAX]; /* Sanity check: if no options and no unknown function, return */ if (options == NULL && unknown == NULL) return (-1); /* Processing options */ bequals = (processing_options & FP_BREAK_ON_EQUALS) == 0 ? 0 : 1; bsemicolon = (processing_options & FP_BREAK_ON_SEMICOLON) == 0 ? 0 : 1; case_sensitive = (processing_options & FP_CASE_SENSITIVE) == 0 ? 0 : 1; require_equals = (processing_options & FP_REQUIRE_EQUALS) == 0 ? 0 : 1; strict_equals = (processing_options & FP_STRICT_EQUALS) == 0 ? 0 : 1; /* Initialize strings */ directive = value = 0; vsize = dsize = 0; /* Resolve the file path */ if (realpath(path, rpath) == 0) return (-1); /* Open the file */ if ((fd = open(rpath, O_RDONLY)) < 0) return (-1); /* Read the file until EOF */ while (r != 0) { r = read(fd, p, 1); /* skip to the beginning of a directive */ while (r != 0 && (isspace(*p) || *p == '#' || comment || (bsemicolon && *p == ';'))) { if (*p == '#') comment = 1; else if (*p == '\n') { comment = 0; line++; } r = read(fd, p, 1); } /* Test for EOF; if EOF then no directive was found */ if (r == 0) { close(fd); return (0); } /* Get the current offset */ curpos = lseek(fd, 0, SEEK_CUR) - 1; if (curpos == -1) { close(fd); return (-1); } /* Find the length of the directive */ for (n = 0; r != 0; n++) { if (isspace(*p)) break; if (bequals && *p == '=') { have_equals = 1; break; } if (bsemicolon && *p == ';') break; r = read(fd, p, 1); } /* Test for EOF, if EOF then no directive was found */ if (n == 0 && r == 0) { close(fd); return (0); } /* Go back to the beginning of the directive */ error = (int)lseek(fd, curpos, SEEK_SET); if (error == (curpos - 1)) { close(fd); return (-1); } /* Allocate and read the directive into memory */ if (n > dsize) { if ((directive = realloc(directive, n + 1)) == NULL) { close(fd); return (-1); } dsize = n; } r = read(fd, directive, n); /* Advance beyond the equals sign if appropriate/desired */ if (bequals && *p == '=') { if (lseek(fd, 1, SEEK_CUR) != -1) r = read(fd, p, 1); if (strict_equals && isspace(*p)) *p = '\n'; } /* Terminate the string */ directive[n] = '\0'; /* Convert directive to lower case before comparison */ if (!case_sensitive) strtolower(directive); /* Move to what may be the start of the value */ if (!(bsemicolon && *p == ';') && !(strict_equals && *p == '=')) { while (r != 0 && isspace(*p) && *p != '\n') r = read(fd, p, 1); } /* An equals sign may have stopped us, should we eat it? */ if (r != 0 && bequals && *p == '=' && !strict_equals) { have_equals = 1; r = read(fd, p, 1); while (r != 0 && isspace(*p) && *p != '\n') r = read(fd, p, 1); } /* If no value, allocate a dummy value and jump to action */ if (r == 0 || *p == '\n' || *p == '#' || (bsemicolon && *p == ';')) { /* Initialize the value if not already done */ if (value == NULL && (value = malloc(1)) == NULL) { close(fd); return (-1); } value[0] = '\0'; goto call_function; } /* Get the current offset */ curpos = lseek(fd, 0, SEEK_CUR) - 1; if (curpos == -1) { close(fd); return (-1); } /* Find the end of the value */ quote = 0; end = 0; while (r != 0 && end == 0) { /* Advance to the next character if we know we can */ if (*p != '\"' && *p != '#' && *p != '\n' && (!bsemicolon || *p != ';')) { r = read(fd, p, 1); continue; } /* * If we get this far, we've hit an end-key */ /* Get the current offset */ charpos = lseek(fd, 0, SEEK_CUR) - 1; if (charpos == -1) { close(fd); return (-1); } /* * Go back so we can read the character before the key * to check if the character is escaped (which means we * should continue). */ error = (int)lseek(fd, -2, SEEK_CUR); if (error == -3) { close(fd); return (-1); } r = read(fd, p, 1); /* * Count how many backslashes there are (an odd number * means the key is escaped, even means otherwise). */ for (n = 1; *p == '\\'; n++) { /* Move back another offset to read */ error = (int)lseek(fd, -2, SEEK_CUR); if (error == -3) { close(fd); return (-1); } r = read(fd, p, 1); } /* Move offset back to the key and read it */ error = (int)lseek(fd, charpos, SEEK_SET); if (error == (charpos - 1)) { close(fd); return (-1); } r = read(fd, p, 1); /* * If an even number of backslashes was counted meaning * key is not escaped, we should evaluate what to do. */ if ((n & 1) == 1) { switch (*p) { case '\"': /* * Flag current sequence of characters * to follow as being quoted (hashes * are not considered comments). */ quote = !quote; break; case '#': /* * If we aren't in a quoted series, we * just hit an inline comment and have * found the end of the value. */ if (!quote) end = 1; break; case '\n': /* * Newline characters must always be * escaped, whether inside a quoted * series or not, otherwise they * terminate the value. */ end = 1; case ';': if (!quote && bsemicolon) end = 1; break; } } else if (*p == '\n') /* Escaped newline character. increment */ line++; /* Advance to the next character */ r = read(fd, p, 1); } /* Get the current offset */ charpos = lseek(fd, 0, SEEK_CUR) - 1; if (charpos == -1) { close(fd); return (-1); } /* Get the length of the value */ n = (uint32_t)(charpos - curpos); if (r != 0) /* more to read, but don't read ending key */ n--; /* Move offset back to the beginning of the value */ error = (int)lseek(fd, curpos, SEEK_SET); if (error == (curpos - 1)) { close(fd); return (-1); } /* Allocate and read the value into memory */ if (n > vsize) { if ((value = realloc(value, n + 1)) == NULL) { close(fd); return (-1); } vsize = n; } r = read(fd, value, n); /* Terminate the string */ value[n] = '\0'; /* Cut trailing whitespace off by termination */ t = value + n; while (isspace(*--t)) *t = '\0'; /* Escape the escaped quotes (replaceall is in string_m.c) */ x = strcount(value, "\\\""); /* in string_m.c */ if (x != 0 && (n + x) > vsize) { if ((value = realloc(value, n + x + 1)) == NULL) { close(fd); return (-1); } vsize = n + x; } if (replaceall(value, "\\\"", "\\\\\"") < 0) { /* Replace operation failed for some unknown reason */ close(fd); return (-1); } /* Remove all new line characters */ if (replaceall(value, "\\\n", "") < 0) { /* Replace operation failed for some unknown reason */ close(fd); return (-1); } /* Resolve escape sequences */ strexpand(value); /* in string_m.c */ call_function: /* Abort if we're seeking only assignments */ if (require_equals && !have_equals) return (-1); found = have_equals = 0; /* reset */ /* If there are no options defined, call unknown and loop */ if (options == NULL && unknown != NULL) { error = unknown(NULL, line, directive, value); if (error != 0) { close(fd); return (error); } continue; } /* Loop through the array looking for a match for the value */ for (n = 0; options[n].directive != NULL; n++) { error = fnmatch(options[n].directive, directive, FNM_NOESCAPE); if (error == 0) { found = 1; /* Call function for array index item */ if (options[n].action != NULL) { error = options[n].action( &options[n], line, directive, value); if (error != 0) { close(fd); return (error); } } } else if (error != FNM_NOMATCH) { /* An error has occurred */ close(fd); return (-1); } } if (!found && unknown != NULL) { /* * No match was found for the value we read from the * file; call function designated for unknown values. */ error = unknown(NULL, line, directive, value); if (error != 0) { close(fd); return (error); } } } close(fd); return (0); }
/* * Takes a pointer to a dpv_config structure containing layout details and * pointer to initial element in a linked-list of dpv_file_node structures, * each presenting a file to process. Executes the `action' function passed-in * as a member to the `config' structure argument. */ int dpv(struct dpv_config *config, struct dpv_file_node *file_list) { char c; uint8_t keep_going; uint8_t nls = FALSE; /* See dialog_prompt_nlstate() */ uint8_t no_overrun = FALSE; uint8_t pprompt_nls = FALSE; /* See dialog_prompt_nlstate() */ uint8_t shrink_label_size = FALSE; mode_t mask; uint16_t options; char *cp; char *fc; char *last; char *name; char *output; const char *status_fmt; const char *path_fmt; enum dpv_display display_type; enum dpv_output output_type; enum dpv_status status; int (*action)(struct dpv_file_node *file, int out); int backslash; int dialog_last_update = 0; int dialog_old_nthfile = 0; int dialog_old_seconds = -1; int dialog_out = STDOUT_FILENO; int dialog_update_usec = 0; int dialog_updates_per_second; int files_left; int max_cols; int nthfile = 0; int output_out; int overall = 0; int pct; int res; int seconds; int status_last_update = 0; int status_old_nthfile = 0; int status_old_seconds = -1; int status_update_usec = 0; int status_updates_per_second; pid_t output_pid; pid_t pid; size_t len; struct dpv_file_node *curfile; struct dpv_file_node *first_file; struct dpv_file_node *list_head; struct timeval now; struct timeval start; char init_prompt[PROMPT_MAX + 1] = ""; /* Initialize globals to default values */ aprompt = NULL; pprompt = NULL; options = 0; action = NULL; backtitle = NULL; debug = FALSE; dialog_test = FALSE; dialog_updates_per_second = DIALOG_UPDATES_PER_SEC; display_limit = DISPLAY_LIMIT_DEFAULT; display_type = DPV_DISPLAY_LIBDIALOG; label_size = LABEL_SIZE_DEFAULT; msg_done = NULL; msg_fail = NULL; msg_pending = NULL; no_labels = FALSE; output = NULL; output_type = DPV_OUTPUT_NONE; pbar_size = PBAR_SIZE_DEFAULT; status_format_custom = NULL; status_updates_per_second = STATUS_UPDATES_PER_SEC; title = NULL; wide = FALSE; /* Process config options (overriding defaults) */ if (config != NULL) { if (config->aprompt != NULL) { if (aprompt == NULL) { aprompt = malloc(DPV_APROMPT_MAX); if (aprompt == NULL) return (-1); } snprintf(aprompt, DPV_APROMPT_MAX, "%s", config->aprompt); } if (config->pprompt != NULL) { if (pprompt == NULL) { pprompt = malloc(DPV_PPROMPT_MAX + 2); /* +2 is for implicit "\n" appended later */ if (pprompt == NULL) return (-1); } snprintf(pprompt, DPV_APROMPT_MAX, "%s", config->pprompt); } options = config->options; action = config->action; backtitle = config->backtitle; debug = config->debug; dialog_test = ((options & DPV_TEST_MODE) != 0); dialog_updates_per_second = config->dialog_updates_per_second; display_limit = config->display_limit; display_type = config->display_type; label_size = config->label_size; msg_done = (char *)config->msg_done; msg_fail = (char *)config->msg_fail; msg_pending = (char *)config->msg_pending; no_labels = ((options & DPV_NO_LABELS) != 0); no_overrun = ((options & DPV_NO_OVERRUN) != 0); output = config->output; output_type = config->output_type; pbar_size = config->pbar_size; status_updates_per_second = config->status_updates_per_second; title = config->title; wide = ((options & DPV_WIDE_MODE) != 0); /* Enforce some minimums (pedantic) */ if (display_limit < -1) display_limit = -1; if (label_size < -1) label_size = -1; if (pbar_size < -1) pbar_size = -1; /* For the mini-pbar, -1 means hide, zero is invalid unless * only one file is given */ if (pbar_size == 0) { if (file_list == NULL || file_list->next == NULL) pbar_size = -1; else pbar_size = PBAR_SIZE_DEFAULT; } /* For the label, -1 means auto-size, zero is invalid unless * specifically requested through the use of options flag */ if (label_size == 0 && no_labels == FALSE) label_size = LABEL_SIZE_DEFAULT; /* Status update should not be zero */ if (status_updates_per_second == 0) status_updates_per_second = STATUS_UPDATES_PER_SEC; } /* config != NULL */ /* Process the type of display we've been requested to produce */ switch (display_type) { case DPV_DISPLAY_STDOUT: debug = TRUE; use_color = FALSE; use_dialog = FALSE; use_libdialog = FALSE; use_xdialog = FALSE; break; case DPV_DISPLAY_DIALOG: use_color = TRUE; use_dialog = TRUE; use_libdialog = FALSE; use_xdialog = FALSE; break; case DPV_DISPLAY_XDIALOG: snprintf(dialog, PATH_MAX, XDIALOG); use_color = FALSE; use_dialog = FALSE; use_libdialog = FALSE; use_xdialog = TRUE; break; default: use_color = TRUE; use_dialog = FALSE; use_libdialog = TRUE; use_xdialog = FALSE; break; } /* display_type */ /* Enforce additional minimums that require knowing our display type */ if (dialog_updates_per_second == 0) dialog_updates_per_second = use_xdialog ? XDIALOG_UPDATES_PER_SEC : DIALOG_UPDATES_PER_SEC; /* Allow forceful override of use_color */ if (config != NULL && (config->options & DPV_USE_COLOR) != 0) use_color = TRUE; /* Count the number of files in provided list of dpv_file_node's */ if (use_dialog && pprompt != NULL && *pprompt != '\0') pprompt_nls = dialog_prompt_nlstate(pprompt); max_cols = dialog_maxcols(); if (label_size == -1) shrink_label_size = TRUE; /* Process file arguments */ for (curfile = file_list; curfile != NULL; curfile = curfile->next) { dpv_nfiles++; /* dialog(3) only expands literal newlines */ if (use_libdialog) strexpandnl(curfile->name); /* Optionally calculate label size for file */ if (shrink_label_size) { nls = FALSE; name = curfile->name; if (curfile == file_list) nls = pprompt_nls; last = (char *)dialog_prompt_lastline(name, nls); if (use_dialog) { c = *last; *last = '\0'; nls = dialog_prompt_nlstate(name); *last = c; } len = dialog_prompt_longestline(last, nls); if ((int)len > (label_size - 3)) { if (label_size > 0) label_size += 3; label_size = len; /* Room for ellipsis (unless NULL) */ if (label_size > 0) label_size += 3; } if (max_cols > 0 && label_size > (max_cols - pbar_size - 9)) label_size = max_cols - pbar_size - 9; } if (debug) warnx("label=[%s] path=[%s] size=%lli", curfile->name, curfile->path, curfile->length); } /* file_list */ /* Optionally process the contents of DIALOGRC (~/.dialogrc) */ if (use_dialog) { res = parse_dialogrc(); if (debug && res == 0) { warnx("Successfully read `%s' config file", DIALOGRC); warnx("use_shadow = %i (Boolean)", use_shadow); warnx("use_colors = %i (Boolean)", use_colors); warnx("gauge_color=[%s] (FBH)", gauge_color); } } else if (use_libdialog) { init_dialog(stdin, stdout); use_shadow = dialog_state.use_shadow; use_colors = dialog_state.use_colors; gauge_color[0] = 48 + dlg_color_table[GAUGE_ATTR].fg; gauge_color[1] = 48 + dlg_color_table[GAUGE_ATTR].bg; gauge_color[2] = dlg_color_table[GAUGE_ATTR].hilite ? 'b' : 'B'; gauge_color[3] = '\0'; end_dialog(); if (debug) { warnx("Finished initializing dialog(3) library"); warnx("use_shadow = %i (Boolean)", use_shadow); warnx("use_colors = %i (Boolean)", use_colors); warnx("gauge_color=[%s] (FBH)", gauge_color); } } /* Enable mini progress bar automatically for stdin streams if unable * to calculate progress (missing `lines:' syntax). */ if (dpv_nfiles <= 1 && file_list != NULL && file_list->length < 0 && !dialog_test) pbar_size = PBAR_SIZE_DEFAULT; /* If $USE_COLOR is set and non-NULL enable color; otherwise disable */ if ((cp = getenv(ENV_USE_COLOR)) != 0) use_color = *cp != '\0' ? 1 : 0; /* Print error and return `-1' if not given at least one name */ if (dpv_nfiles == 0) { warnx("%s: no labels provided", __func__); return (-1); } else if (debug) warnx("%s: %u label%s provided", __func__, dpv_nfiles, dpv_nfiles == 1 ? "" : "s"); /* If only one file and pbar size is zero, default to `-1' */ if (dpv_nfiles <= 1 && pbar_size == 0) pbar_size = -1; /* Print some debugging information */ if (debug) { warnx("%s: %s(%i) max rows x cols = %i x %i", __func__, use_xdialog ? XDIALOG : DIALOG, use_libdialog ? 3 : 1, dialog_maxrows(), dialog_maxcols()); } /* Xdialog(1) updates a lot slower than dialog(1) */ if (dialog_test && use_xdialog) increment = XDIALOG_INCREMENT; /* Always add implicit newline to pprompt (when specified) */ if (pprompt != NULL && *pprompt != '\0') { len = strlen(pprompt); /* * NOTE: pprompt = malloc(PPROMPT_MAX + 2) * NOTE: (see getopt(2) section above for pprompt allocation) */ pprompt[len++] = '\\'; pprompt[len++] = 'n'; pprompt[len++] = '\0'; } /* Xdialog(1) requires newlines (a) escaped and (b) in triplicate */ if (use_xdialog && pprompt != NULL) { /* Replace `\n' with `\n\\n\n' in pprompt */ len = strlen(pprompt); len += strcount(pprompt, "\\n") * 2; if (len > DPV_PPROMPT_MAX) errx(EXIT_FAILURE, "%s: Oops, pprompt buffer overflow " "(%zu > %i)", __func__, len, DPV_PPROMPT_MAX); if (replaceall(pprompt, "\\n", "\n\\n\n") < 0) err(EXIT_FAILURE, "%s: replaceall()", __func__); } /* libdialog requires literal newlines */ else if (use_libdialog && pprompt != NULL) strexpandnl(pprompt); /* Xdialog(1) requires newlines (a) escaped and (b) in triplicate */ if (use_xdialog && aprompt != NULL) { /* Replace `\n' with `\n\\n\n' in aprompt */ len = strlen(aprompt); len += strcount(aprompt, "\\n") * 2; if (len > DPV_APROMPT_MAX) errx(EXIT_FAILURE, "%s: Oops, aprompt buffer overflow " " (%zu > %i)", __func__, len, DPV_APROMPT_MAX); if (replaceall(aprompt, "\\n", "\n\\n\n") < 0) err(EXIT_FAILURE, "%s: replaceall()", __func__); } /* libdialog requires literal newlines */ else if (use_libdialog && aprompt != NULL) strexpandnl(aprompt); /* * Warn user about an obscure dialog(1) bug (neither Xdialog(1) nor * libdialog are affected) in the `--gauge' widget. If the first non- * whitespace letter of "{new_prompt}" in "XXX\n{new_prompt}\nXXX\n" * is a number, the number can sometimes be mistaken for a percentage * to the overall progressbar. Other nasty side-effects such as the * entire prompt not displaying or displaying improperly are caused by * this bug too. * * NOTE: When we can use color, we have a work-around... prefix the * output with `\Zn' (used to terminate ANSI and reset to normal). */ if (use_dialog && !use_color) { backslash = 0; /* First, check pprompt (falls through if NULL) */ fc = pprompt; while (fc != NULL && *fc != '\0') { if (*fc == '\n') /* leading literal newline OK */ break; if (!isspace(*fc) && *fc != '\\' && backslash == 0) break; else if (backslash > 0 && *fc != 'n') break; else if (*fc == '\\') { backslash++; if (backslash > 2) break; /* we're safe */ } fc++; } /* First non-whitespace character that dialog(1) will see */ if (fc != NULL && *fc >= '0' && *fc <= '9') warnx("%s: WARNING! text argument to `-p' begins with " "a number (not recommended)", __func__); else if (fc > pprompt) warnx("%s: WARNING! text argument to `-p' begins with " "whitespace (not recommended)", __func__); /* * If no pprompt or pprompt is all whitespace, check the first * file name provided to make sure it is alright too. */ if ((pprompt == NULL || *fc == '\0') && file_list != NULL) { first_file = file_list; fc = first_file->name; while (fc != NULL && *fc != '\0' && isspace(*fc)) fc++; /* First non-whitespace char that dialog(1) will see */ if (fc != NULL && *fc >= '0' && *fc <= '9') warnx("%s: WARNING! File name `%s' begins " "with a number (use `-p text' for safety)", __func__, first_file->name); } } dprompt_init(file_list); /* Reads: label_size pbar_size pprompt aprompt dpv_nfiles */ /* Inits: dheight and dwidth */ if (!debug) { /* Internally create the initial `--gauge' prompt text */ dprompt_recreate(file_list, (struct dpv_file_node *)NULL, 0); /* Spawn [X]dialog(1) `--gauge', returning pipe descriptor */ if (use_libdialog) { status_printf(""); dprompt_libprint(pprompt, aprompt, 0); } else { dprompt_sprint(init_prompt, pprompt, aprompt); dialog_out = dialog_spawn_gauge(init_prompt, &pid); dprompt_dprint(dialog_out, pprompt, aprompt, 0); } } /* !debug */ /* Seed the random(3) generator */ if (dialog_test) srandom(0xf1eeface); /* Set default/custom status line format */ if (dpv_nfiles > 1) { snprintf(status_format_default, DPV_STATUS_FORMAT_MAX, "%s", DPV_STATUS_MANY); status_format_custom = config->status_many; } else { snprintf(status_format_default, DPV_STATUS_FORMAT_MAX, "%s", DPV_STATUS_SOLO); status_format_custom = config->status_solo; } /* Add test mode identifier to default status line if enabled */ if (dialog_test && (strlen(status_format_default) + 12) < DPV_STATUS_FORMAT_MAX) strcat(status_format_default, " [TEST MODE]"); /* Verify custom status format */ status_fmt = fmtcheck(status_format_custom, status_format_default); if (status_format_custom != NULL && status_fmt == status_format_default) { warnx("WARNING! Invalid status_format configuration `%s'", status_format_custom); warnx("Default status_format `%s'", status_format_default); } /* Record when we started (used to prevent updating too quickly) */ (void)gettimeofday(&start, (struct timezone *)NULL); /* Calculate number of microseconds in-between sub-second updates */ if (status_updates_per_second != 0) status_update_usec = 1000000 / status_updates_per_second; if (dialog_updates_per_second != 0) dialog_update_usec = 1000000 / dialog_updates_per_second; /* * Process the file list [serially] (one for each argument passed) */ files_left = dpv_nfiles; list_head = file_list; for (curfile = file_list; curfile != NULL; curfile = curfile->next) { keep_going = TRUE; output_out = -1; pct = 0; nthfile++; files_left--; if (dpv_interrupt) break; if (dialog_test) pct = 0 - increment; /* Attempt to spawn output program for this file */ if (!dialog_test && output != NULL) { mask = umask(0022); (void)umask(mask); switch (output_type) { case DPV_OUTPUT_SHELL: output_out = shell_spawn_pipecmd(output, curfile->name, &output_pid); break; case DPV_OUTPUT_FILE: path_fmt = fmtcheck(output, "%s"); if (path_fmt == output) len = snprintf(pathbuf, PATH_MAX, output, curfile->name); else len = snprintf(pathbuf, PATH_MAX, "%s", output); if (len >= PATH_MAX) { warnx("%s:%d:%s: pathbuf[%u] too small" "to hold output argument", __FILE__, __LINE__, __func__, PATH_MAX); return (-1); } if ((output_out = open(pathbuf, O_CREAT|O_WRONLY, DEFFILEMODE & ~mask)) < 0) { warn("%s", pathbuf); return (-1); } break; default: break; } } while (!dpv_interrupt && keep_going) { if (dialog_test) { usleep(50000); pct += increment; dpv_overall_read += (int)(random() / 512 / dpv_nfiles); /* 512 limits fake readout to Megabytes */ } else if (action != NULL) pct = action(curfile, output_out); if (no_overrun || dialog_test) keep_going = (pct < 100); else { status = curfile->status; keep_going = (status == DPV_STATUS_RUNNING); } /* Get current time and calculate seconds elapsed */ gettimeofday(&now, (struct timezone *)NULL); now.tv_sec = now.tv_sec - start.tv_sec; now.tv_usec = now.tv_usec - start.tv_usec; if (now.tv_usec < 0) now.tv_sec--, now.tv_usec += 1000000; seconds = now.tv_sec + (now.tv_usec / 1000000.0); /* Update dialog (be it dialog(3), dialog(1), etc.) */ if ((dialog_updates_per_second != 0 && ( seconds != dialog_old_seconds || now.tv_usec - dialog_last_update >= dialog_update_usec || nthfile != dialog_old_nthfile )) || pct == 100 ) { /* Calculate overall progress (rounding up) */ overall = (100 * nthfile - 100 + pct) / dpv_nfiles; if (((100 * nthfile - 100 + pct) * 10 / dpv_nfiles % 100) > 50) overall++; dprompt_recreate(list_head, curfile, pct); if (use_libdialog && !debug) { /* Update dialog(3) widget */ dprompt_libprint(pprompt, aprompt, overall); } else { /* stdout, dialog(1), or Xdialog(1) */ dprompt_dprint(dialog_out, pprompt, aprompt, overall); fsync(dialog_out); } dialog_old_seconds = seconds; dialog_old_nthfile = nthfile; dialog_last_update = now.tv_usec; } /* Update the status line */ if ((use_libdialog && !debug) && status_updates_per_second != 0 && ( keep_going != TRUE || seconds != status_old_seconds || now.tv_usec - status_last_update >= status_update_usec || nthfile != status_old_nthfile ) ) { status_printf(status_fmt, dpv_overall_read, (dpv_overall_read / (seconds == 0 ? 1 : seconds) * 1.0), 1, /* XXX until we add parallelism XXX */ files_left); status_old_seconds = seconds; status_old_nthfile = nthfile; status_last_update = now.tv_usec; } } if (!dialog_test && output_out >= 0) { close(output_out); waitpid(output_pid, (int *)NULL, 0); } if (dpv_abort) break; /* Advance head of list when we hit the max display lines */ if (display_limit > 0 && nthfile % display_limit == 0) list_head = curfile->next; } if (!debug) { if (use_libdialog) end_dialog(); else { close(dialog_out); waitpid(pid, (int *)NULL, 0); } if (!dpv_interrupt) printf("\n"); } else warnx("%s: %lli overall read", __func__, dpv_overall_read); if (dpv_interrupt || dpv_abort) return (-1); else return (0); }
int main(int argc, char **argv) { FILE *fd, *fdw; char *orgbuf,*buf, *p, *ptr, *tt; int size, n, j; struct darray_s *darr, *darr_line; struct darray_s **item; char filename[50], outfile[50]; if (argc < 2) { printf("format error: csv2json {filename}\n"); exit(0); } strcpy(filename, argv[1]); strcpy(outfile, argv[1]); strcat(outfile, ".json"); printf("filename:%s, outfile:%s\n", filename, outfile); fd = fopen(filename, "r+"); if (fd == NULL) { perror("open input file err"); exit(0); } //fdw = fopen(strcat(argv[1],".json"), "w"); fdw = fopen(outfile, "w"); if (fdw == NULL) { perror("open write file err"); exit(0); } /* load data into dynamic array */ orgbuf = buf = (char*)calloc(1, LINE); darr = (u_char *)darray_calloc(linecount_fd(fd), sizeof(buf)); while (fgets(buf, LINE, fd)) { // printf("buf:%s\n", buf); darr_line = darray_calloc(strcount(buf, ',')+1, LINE); //printf("%p\n", darr_line); tt = darray_pushback(darr); //printf("1 values: %p\n", tt); memcpy(tt, &darr_line, sizeof(darr_line)); trim(buf); while (p = strchr(buf, ',')) { size = p-buf; ptr = darray_pushback(darr_line); //printf("2 buf:%s, size:%d, ptr:%p\n", buf, size, ptr); strncpy(ptr, buf, size); buf = p+1; trim(buf); } ptr = darray_pushback(darr_line); size = strlen(buf); //printf("2 buf:%s, size:%d, ptr:%p\n", buf, size, ptr); strncpy(ptr, buf, size); buf = orgbuf; memset(buf, 0, LINE); } /* write json file */ item = darr->da_values; if (darray_count(darr) > 3) fprintf(fdw, "["); for (n=3; n<darray_count(darr); n++) { fprintf(fdw, "{"); for (j=0; j<darray_count(*item); j++) { //printf("tt:%s\n", item[1]->da_values+j*item[1]->da_size); if (strcmp(item[1]->da_values+j*item[1]->da_size, "0") == 0) fprintf(fdw, "\"%s\":\"%s\"", item[0]->da_values+j*item[n]->da_size, item[n]->da_values+j*item[n]->da_size); else if (strcmp(item[1]->da_values+j*item[1]->da_size, "2") == 0) { fprintf(fdw, "\"%s\":\"%s\"", item[0]->da_values+j*item[n]->da_size, item[n]->da_values+j*item[n]->da_size); /* char tt[1024]; memset(tt, 0, 1024); printf("len:%d\n", strlen(*(item[n]->da_values+j*item[n]->da_size))); memcpy(tt, item[n]->da_values+j*item[n]->da_size+1, strlen(item[n]->da_values+j*item[n]->da_size)-2); fprintf(fdw, "\"%s\":%s", item[0]->da_values+j*item[n]->da_size, item[n]->da_values+j*item[n]->da_size); */ } else if (strcmp(item[1]->da_values+j*item[1]->da_size, "1") == 0) fprintf(fdw, "\"%s\":%d", item[0]->da_values+j*item[n]->da_size, atoi(item[n]->da_values+j*item[n]->da_size)); else printf("data tyep err."); if (j<darray_count(*item)-1) fprintf(fdw, ", "); } if (n < darray_count(darr)-1) fprintf(fdw, "}, \n"); else fprintf(fdw, "}"); } if (darray_count(darr) > 3) fprintf(fdw, "]\n"); free(orgbuf); darray_free(darr); fclose(fd); fclose(fdw); return 0; }