连接路径和基名

jov*_*eha 4 c posix

basename(3)dirname(3)可以将绝对路径拆分为各自的组件.

没有使用snprintf(3),是否有一个自然的posix兼容库调用反向 - 获取目录和文件名并连接它们?

手动连接对我来说很好,但有时会变得有点单调乏味.

dfa*_*dfa 7

据我所知,POSIX中没有这样的功能.但是在GNU libc手册中有一个很好的辅助函数:

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;
 }
Run Code Online (Sandbox Code Playgroud)

用法:

const char *path = concat(directory, "/", file);
Run Code Online (Sandbox Code Playgroud)