148 {
149 const char *tmp =
str;
150 char *result;
151 int found = 0;
152 int length, reslen;
153 int oldlen = strlen(oldstr);
154 int newlen = strlen(newstr);
155 int limit = (
count != NULL && *
count > 0) ? *count : -1;
156
158 while ((tmp = strstr(tmp, oldstr)) != NULL && found != limit)
159 found++, tmp += oldlen;
160
161 length = strlen(
str) + found * (newlen - oldlen);
162 if ((result = (
char *)
rtalloc(length + 1)) == NULL) {
163 rterror(
_(
"strreplace: Not enough memory"));
164 found = -1;
165 }
166 else {
168 limit = found;
169 reslen = 0;
170
171
172 while ((limit-- > 0) && (tmp = strstr(tmp, oldstr)) != NULL) {
173 length = (tmp -
str);
174 strncpy(result + reslen,
str, length);
175 strcpy(result + (reslen += length), newstr);
176
177 reslen += newlen;
178 tmp += oldlen;
180 }
181 strcpy(result + reslen,
str);
182 }
183
184 if (count != NULL) *
count = found;
185 return result;
186}
void rterror(const char *fmt,...)
Wrappers used for reporting errors and info.
void * rtalloc(size_t size)
Wrappers used for managing memory.