int main(void) { char *x, *y, *z, *za; x = "{}%$"; strnsubst(&x, "%$", "{} enpury!", 255); y = x; strnsubst(&y, "}{}", "ybir", 255); z = y; strnsubst(&z, "{", "v ", 255); za = z; strnsubst(&z, NULL, za, 255); if (strcmp(z, "v ybir enpury!") == 0) printf("strnsubst() seems to work!\n"); else printf("strnsubst() is broken.\n"); printf("%s\n", z); free(x); free(y); free(z); free(za); return 0; }
/* * Do things necessary before run()'ing, such as -I substitution, * and then call run(). */ static void prerun(int argc, char *argv[]) { char **tmp, **tmp2, **avj; int repls; repls = Rflag; if (argc == 0 || repls == 0) { *xp = NULL; run(argv); return; } avj = argv; /* * Allocate memory to hold the argument list, and * a NULL at the tail. */ tmp = malloc((argc + 1) * sizeof(char**)); if (tmp == NULL) { warnx("malloc failed"); xexit(*argv, 1); } tmp2 = tmp; /* * Save the first argument and iterate over it, we * cannot do strnsubst() to it. */ if ((*tmp++ = strdup(*avj++)) == NULL) { warnx("strdup failed"); xexit(*argv, 1); } /* * For each argument to utility, if we have not used up * the number of replacements we are allowed to do, and * if the argument contains at least one occurrence of * replstr, call strnsubst(), else just save the string. * Iterations over elements of avj and tmp are done * where appropriate. */ while (--argc) { *tmp = *avj++; if (repls && strstr(*tmp, replstr) != NULL) { strnsubst(tmp++, replstr, inpline, (size_t)Sflag); if (repls > 0) repls--; } else { if ((*tmp = strdup(*tmp)) == NULL) { warnx("strdup failed"); xexit(*argv, 1); } tmp++; } } /* * Run it. */ *tmp = NULL; run(tmp2); /* * Walk from the tail to the head, free along the way. */ for (; tmp2 != tmp; tmp--) free(*tmp); /* * Now free the list itself. */ free(tmp2); /* * Free the input line buffer, if we have one. */ if (inpline != NULL) { free(inpline); inpline = NULL; } }