我需要从两个字符串构造一个文件的路径.我可以使用它(虽然没有经过测试):
/* DON'T USE THIS CODE! */
/* cmp means component */
char *path_cmp1 = "/Users/john/";
char *path_cmp2 = "foo/bar.txt";
unsigned len = strlen(path_cmp1);
char *path = path_cmp1;
for (int i = 0; i < strlen(path_cmp2); i++) {
path[len + i] = path_cmp2[i];
}
Run Code Online (Sandbox Code Playgroud)
但这可能会导致内存损坏.有没有更好的方法来做到这一点,或者标准库中是否有这样的功能?
#include <stdlib.h>
#include <string.h>
char *join(const char* s1, const char* s2)
{
char* result = malloc(strlen(s1) + strlen(s2) + 1);
if (result) // thanks @pmg
{
strcpy(result, s1);
strcat(result, s2);
}
return result;
}
Run Code Online (Sandbox Code Playgroud)
这很简单,可以在适当的位置编写,尤其是当您有多个字符串要连接时.
请注意,这些函数返回其目标参数,因此您可以编写
char* result = malloc(strlen(s1) + strlen(s2) + 1);
assert(result);
strcat(strcpy(result, s1), s2);
Run Code Online (Sandbox Code Playgroud)
但这不太可读.
#include <stdio.h>
char *a = "hello ";
char *b = "goodbye";
char *joined;
asprintf(&joined, "%s%s", a, b)
Run Code Online (Sandbox Code Playgroud)