I want to append two strings. I used the following command:
new_str = strcat(str1, str2);
This command changes the value of str1
man page of strcat says that arg1 and arg2 are appended to arg1.. and returns the pointer of s1. If you dont want disturb str1,str2 then you have write your own function.
char * my_strcat(const char * str1, const char * str2)
{
char * ret = malloc(strlen(str1)+strlen(str2));
if(ret!=NULL)
{
sprintf(ret, "%s%s", str1, str2);
return ret;
}
return NULL;
}
Hope this solves your purpose
You'll have to strncpy
str1
into new_string
first then.
I needed to append substrings to create an ssh command, I solved with sprintf
(Visual Studio 2013)
char gStrSshCommand[SSH_COMMAND_MAX_LEN]; // declare ssh command string
strcpy(gStrSshCommand, ""); // empty string
void appendSshCommand(const char *substring) // append substring
{
sprintf(gStrSshCommand, "%s %s", gStrSshCommand, substring);
}
do the following:
strcat(new_str,str1);
strcat(new_str,str2);