开发者

How to Concatenate 2 C strings, without overwriting any terminating Null characters?

开发者 https://www.devze.com 2023-01-03 05:14 出处:网络
I am trying to set up a list of file names for a parameter to SHFileOperation. I want to be able to concatenate a file name onto the char array, but i dont want to get rid of the terminating character

I am trying to set up a list of file names for a parameter to SHFileOperation. I want to be able to concatenate a file name onto the char array, but i dont want to get rid of the terminating character. for example, I want this:

C:\...\0E:\...\0F:\...\0\0

when i use strcat(), it overwrites the null, so it looks like

C:\.开发者_开发百科..E:\...F:\...0\

Is there any easy way to do this? or am i going to have to code a new strcat for myself?


The code is pretty straightforward. Use a helper pointer to track where the next string should start. To update the tracker pointer, increment by the length of the string +1:

const char *data[] = { "a", "b", "c" };
size_t data_count = sizeof(data) / sizeof(*data);
size_t d;
size_t buffer_size;
char *buffer;
char *next;

// calculate the size of the buffer 
for (d = 0; d < data_count; ++d)
    buffer_size += (strlen(data[d] + 1);
buffer_size += 1;

buffer = malloc(buffer_size);

// Next will track where we write the next string
next = buffer;

for (d = 0; d < data_count; ++d)
{
    strcpy(next, data[d]);

    // Update next to point to the first character after the terminating NUL
    next += strlen(data[d]) + 1;
}
*next = '\0';


Use memcpy.

memcpy(dest, src1, strlen(src1)+1);
memcpy(&dest[strlen(src1)+1], src2, strlen(src2)+1);


Using the GNU stpcpy() may be slightly more elegant, if you know beforehand the maximum 'length' of the resulting char array.

char *src[] = {"C:\\foo", "E:\\bar", "F:\\foobar", 0};
char dst[MY_MAX_LEN], *p = dst;
int i;

for (i = 0; src[i]; i++)
    p = stpcpy(p, src) + 1;
*p = 0;
assert(p < dst + sizeof dst);

If needed, stpcpy() can be defined as:

char *stpcpy(char * restrict dst, const char * restrict src)
{
    return strcpy(dst, src) + strlen(src);
}


just use strcat to append to the original string, but add one to the offset so you're bypassing the previous string's 0 terminator.

// an example

    char testString [256];

     strcpy (testString, "Test1");

     strcat (testString + strlen(testString)+1, "Test2");
     strcat (testString + strlen(testString)+1, "Test3");

testString will now contain "Test1\0Test2\0Test3\0"

0

精彩评论

暂无评论...
验证码 换一张
取 消