I'm working on a project of mine which required multiple calls to strncat(), and it came to me that it'd have been much easier if C also had something like "file://" + getenv("HOME") + filename for string generation. So I built a function that works in a similar fashion, it is a variadic function, the arguments are NULL terminated.
Usage: char *str = mutant_string ("file://", getenv ("HOME"), filename, NULL);
It's obviously up to the user to free the memory str allocated.
The code:-
char *mutant_string (const char *s, ...) {
va_list argv;
va_start (argv, s);
char *return_string = strdup (s);
size_t realsize, nmemb;
realsize = strlen (return_string); // Or initial size
char *c, *ptr;
while ((c = va_arg(argv, char*)))
{
nmemb = strlen (c);
realsize += nmemb;
ptr = realloc (return_string, sizeof(char) * (realsize + 1));
if (!ptr) {
perror ("realloc");
free (return_string);
va_end (argv);
return NULL;
}
return_string = ptr;
strncat (return_string, c, nmemb);
}
return_string[realsize] = 0;
va_end (argv);
return return_string;
}
I welcome any kind of observations or opinions. Let me know if there's an external library or function that does exactly this and something that I can read.
Thank you.