Revised version of search_replace, this time replacing all instances of pattern and with memory allocation moved outside the function. Any comments? It looks a bit crazy, so I could really need a better solution.
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
static char *search_replace(
char *dest,
const char *src,
size_t size,
const char *pattern,
const char *replace)
{
size_t src_len = strlen(src);
size_t pattern_len = strlen(pattern);
size_t replace_len = strlen(replace);
char *needle, *tmp;
int offset_src = 0; /* Current position in src */
int offset_tmp = 0; /* Current position in tmp */
int diff;
if ((tmp = malloc(size)) == NULL)
{
puts("Memory allocation error");
return 0;
}
if ((needle = strstr(&src[offset_src], pattern)) == NULL)
{
printf("Pattern not found\n");
return 0;
}
do
{
if (needle == NULL)
break;
else
printf("Found pattern: \"%s\"\n", pattern);
diff = (int) needle - (int) &src[offset_src];
strncpy(&tmp[offset_tmp], &src[offset_src], diff);
offset_tmp += diff;
offset_src += diff + pattern_len;
strncpy(&tmp[offset_tmp], replace, replace_len);
offset_tmp += replace_len;
}
while ((needle = strstr(&src[offset_src], pattern)) != NULL);
strncpy(&tmp[offset_tmp], &src[offset_src], src_len-offset_src);
offset_tmp += src_len-offset_src;
strncpy(dest, tmp, offset_tmp);
dest[offset_tmp] = '\0';
free(tmp);
return dest;
}
int main(void)
{
char *s = "012345remove_me6789 remove_meabcdefgh";
char *buf = malloc(100);
search_replace(buf, s, 100, "remove_me", "");
printf("%s\n", buf);
return 0;
}