我知道strcat(dest, src)将src附加到dest,并返回dest。现在,如果我想将dest附加到src -即在dest中的dest之前插入字符串src -有什么方法可以做到吗?
我尝试使用strcat,类似于
dest = strcat(dest, src);但不能让它工作。
发布于 2009-11-04 16:46:42
下面是一个经过简单测试的strlprecat()实现,它或多或少遵循了OpenBSD的'strlxxx()‘函数风格:
因此,此函数永远不会导致缓冲区溢出,但可能会导致字符串被截断(因此会破坏缓冲区中的原始字符串)。
无论如何,我发现一个类似的函数偶尔也很有用:
size_t
strlprecat( char* dst, const char * src, size_t size)
{
size_t dstlen = strnlen( dst, size);
size_t srclen = strlen( src);
size_t srcChars = srclen;
size_t dstChars = dstlen;
if (0 == size) {
/* we can't write anything into the dst buffer */
/* -- bail out */
return( srclen + dstlen);
}
/* determine how much space we need to add to front of dst */
if (srcChars >= size) {
/* we can't even fit all of src into dst */
srcChars = size - 1;
}
/* now figure out how many of dst's characters will fit in the remaining buffer */
if ((srcChars + dstChars) >= size) {
dstChars = size - srcChars - 1;
}
/* move dst to new location, truncating if necessary */
memmove( dst+srcChars, dst, dstChars);
/* copy src into the spot we just made for it */
memcpy( dst, src, srcChars);
/* make sure the whole thing is terminated properly */
dst[srcChars + dstChars] = '\0';
return( srclen + dstlen);
}可以随意修改它,这样它就不会处理缓冲区长度(盲目地将内容移动到所需的位置),或者在缓冲区不够大的情况下只返回错误而不做任何操作。
哦,当然,如果你修复了任何bug,也可以发表评论。
发布于 2009-11-04 15:07:11
如果您希望在不修改src的情况下完成此操作,则可以分两步完成:
strcpy(temp, src);
strcat(temp, dest);为了清楚起见,省略了所有错误处理和确定足够大的temp大小。
https://stackoverflow.com/questions/1672112
复制相似问题