]>
git.saurik.com Git - apple/shell_cmds.git/blob - xargs/strnsubst.c
1 /* $xMach: strnsubst.c,v 1.3 2002/02/23 02:10:24 jmallett Exp $ */
4 * Copyright (c) 2002 J. Mallett. All rights reserved.
5 * You may do whatever you want with this file as long as
6 * the above copyright and this notice remain intact, along
7 * with the following statement:
8 * For the man who taught me vi, and who got too old, too young.
11 #include <sys/cdefs.h>
12 __FBSDID("$FreeBSD: src/usr.bin/xargs/strnsubst.c,v 1.7 2004/10/18 15:40:47 cperciva Exp $");
19 void strnsubst(char **, const char *, const char *, size_t);
22 * Replaces str with a string consisting of str with match replaced with
23 * replstr as many times as can be done before the constructed string is
24 * maxsize bytes large. It does not free the string pointed to by str, it
25 * is up to the calling program to be sure that the original contents of
26 * str as well as the new contents are handled in an appropriate manner.
27 * If replstr is NULL, then that internally is changed to a nil-string, so
28 * that we can still pretend to do somewhat meaningful substitution.
29 * No value is returned.
32 strnsubst(char **str
, const char *match
, const char *replstr
, size_t maxsize
)
39 s2
= calloc(maxsize
, 1);
46 if (match
== NULL
|| replstr
== NULL
|| maxsize
== strlen(s1
)) {
47 strlcpy(s2
, s1
, maxsize
);
52 this = strstr(s1
, match
);
55 if ((strlen(s2
) + strlen(s1
) + strlen(replstr
) -
56 strlen(match
) + 1) > maxsize
) {
57 strlcat(s2
, s1
, maxsize
);
60 strncat(s2
, s1
, (uintptr_t)this - (uintptr_t)s1
);
62 s1
= this + strlen(match
);
79 strnsubst(&x
, "%$", "{} enpury!", 255);
81 strnsubst(&y
, "}{}", "ybir", 255);
83 strnsubst(&z
, "{", "v ", 255);
85 strnsubst(&z
, NULL
, za
, 255);
86 if (strcmp(z
, "v ybir enpury!") == 0)
87 printf("strnsubst() seems to work!\n");
89 printf("strnsubst() is broken.\n");