basename(3)和 dirname(3)可以将绝对路径拆分为各自的组件。
没有使用 snprintf(3),是否有一个自然的posix兼容库调用,它会执行反向操作 - 获取目录和文件名并将它们连接起来?
手动连接对我来说很好,但有时会变得有点单调乏味。
答案 0 :(得分:7)
据我所知,POSIX中没有这样的功能。但是在GNU libc manual there is a nice helper function:
char *concat (const char *str, ...)
{
va_list ap;
size_t allocated = 100;
char *result = (char *) malloc (allocated);
if (result != NULL)
{
char *newp;
char *wp;
va_start (ap, str);
wp = result;
for (s = str; s != NULL; s = va_arg (ap, const char *))
{
size_t len = strlen (s);
/* Resize the allocated memory if necessary. */
if (wp + len + 1 > result + allocated)
{
allocated = (allocated + len) * 2;
newp = (char *) realloc (result, allocated);
if (newp == NULL)
{
free (result);
return NULL;
}
wp = newp + (wp - result);
result = newp;
}
wp = mempcpy (wp, s, len);
}
/* Terminate the result string. */
*wp++ = '\0';
/* Resize memory to the optimal size. */
newp = realloc (result, wp - result);
if (newp != NULL)
result = newp;
va_end (ap);
}
return result;
}
用法:
const char *path = concat(directory, "/", file);