summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--main.c4
-rw-r--r--replace.c46
2 files changed, 50 insertions, 0 deletions
diff --git a/main.c b/main.c
index 8efc66c..a0b7b4d 100644
--- a/main.c
+++ b/main.c
@@ -1,4 +1,5 @@
#include <stdio.h>
+#include <stdlib.h>
#include "replace.h"
int
@@ -8,5 +9,8 @@ main(void)
ret = replaceinfile("input.txt", "output.txt", "%PLACEHOLDER%", "replacement string");
if (ret == 0)
puts("failed");
+ char *rep = replaceinmemory("this string this string is a test string", "string", "word");
+ printf("%s\n", rep);
+ free(rep);
return 0;
}
diff --git a/replace.c b/replace.c
index 1860d9e..dcfd1ed 100644
--- a/replace.c
+++ b/replace.c
@@ -37,6 +37,14 @@ getfilelength(FILE *fp)
return retval;
}
+void
+replaceappendchar(char *dest, char ch)
+{
+ int len = strlen(dest);
+ dest[len] = ch;
+ dest[len+1] = '\0';
+}
+
int
replaceinfile(char *originalfile, char *destinationfile, char *placeholder, char *replacement)
{
@@ -78,3 +86,41 @@ replaceinfile(char *originalfile, char *destinationfile, char *placeholder, char
free(filebuffer);
return 1;
}
+
+char *
+replaceinmemory(char *src, char *placeholder, char *replacement)
+{
+ /*
+ * replace every placeholder with replacement in source src
+ * return pointer to string, NULL if no placement found
+ * user must free the returned memory
+ */
+ char *dest = NULL;
+ size_t destsize;
+ char *substr = strstr(src, placeholder);
+ if (!substr)
+ return NULL;
+ /* initial dest size if only one placeholder exists */
+ destsize = (strlen(src)-strlen(placeholder))+strlen(replacement+1);
+ dest = malloc(destsize);
+ if (!dest)
+ return NULL;
+ dest[0] = '\0'; /* junk in memory, we need [0] to be null for strlen() later */
+ for (size_t i = 0; i < strlen(src); i++)
+ {
+ if (i == (substr-src))
+ {
+ i += strlen(placeholder);
+ substr++;
+ substr = strstr(substr, placeholder);
+ if (substr)
+ {
+ destsize = (destsize-strlen(placeholder))+strlen(replacement)+1;
+ dest = realloc(dest, destsize);
+ }
+ strcat(dest, replacement);
+ }
+ replaceappendchar(dest, src[i]);
+ }
+ return dest;
+}