1

Hey all, My question is, how do I append two C-style strings into one?

Being babied by the C++ way of doing things (std::string), I've never touched C-style strings and need to learn more about them for my current development project. For example:

 char[] filename = "picture.png";
 char[] directory = "/rd/";
 //how would I "add" together directory and filename into one char[]?

Thanks in advance.

epicasian
  • 45
  • 1
  • 1
  • 5
  • 1
    Why not just add them as std::strings and use c_str() or &string[0] to convert to C string? – Puppy Nov 22 '10 at 23:59
  • I can't because I'm compiling for Dreamcast, and the string library hasn't been ported. – epicasian Nov 23 '10 at 00:02
  • Note that string literals are of type `const char*` and not `char*` and the code shown will only compile on non-conforming compilers. – pmr Nov 23 '10 at 00:07

6 Answers6

3

Use strcat().

See here: http://www.cplusplus.com/reference/clibrary/cstring/strcat/

xxpor
  • 473
  • 3
  • 11
0
#include <stdlib.h>
#include <string.h>

// ...

char * fullpath;

fullpath = malloc(strlen(directory)+strlen(filename)+1);
if (fullpath == NULL)
{
  // memory allocation failure 
}
strcpy(fullpath, directory);
strcat(fullpath, filename);
0

You need a big enough buffer, that, assuming you don't have filename's and directory's size handy at compile-time, you must get at run-time, like so

char *buf = (char *) malloc (strlen (filename) + strlen (directory) + 1);
if (!buf) { /* no memory, typically */ }
strcpy (buf, filename);
strcat (buf, directory);
dennycrane
  • 2,301
  • 18
  • 15
0

Keep in mind you're working a lower level, and it's not going to allocate memory for you automatically. You have to allocate enough memory to hold the two strings plus a null terminator and then copy them into place.

JOTN
  • 6,120
  • 2
  • 26
  • 31
0

Be sure to declare/allocate a char array large enough to hold both filename and directory. Then, use strcat() (or strncat()) as xxpor suggested.

pr1268
  • 1,176
  • 3
  • 9
  • 16
0

You have to think how your "string" is actually represented in memory. In C, strings are buffers of allocated memory terminated by a 0 byte.

filename  |p|i|c|t|u|r|e|0|
directory |/|r|d|/|0|

What you require is a new memory space to copy the memory content of both strings together and the last 0 byte.

path      |p|i|c|t|u|r|e|/|r|d|/|0|

Which gives this code:

int lenFilename = strlen(filename); // 7
int lenDirectory = strlen(directory); // 4
int lenPath = lenFilename + lenDirectory; // 11 I can count
char* path = malloc(lenPath + 1);
memcpy(path, filename, lenFilename);
memcpy(path + lenFilename, directory, lenDirectory);
path[lenPath] = 0; // Never EVER forget the terminating 0 !

...

free(path); // You should not forget to free allocated memory when you are done

(There may be an off-by-1 mistake in this code, it is not actually tested... It is 01:00am and I should go to sleep!)

Vincent Robert
  • 35,564
  • 14
  • 82
  • 119