home *** CD-ROM | disk | FTP | other *** search
/ ftp.ncftp.com / ftp.ncftp.com.zip / ftp.ncftp.com / libncftp / older_versions / libncftp-3.1.5-src.tar.gz / libncftp-3.1.5-src.tar / libncftp-3.1.5 / Strn / Dynscpy.c < prev    next >
C/C++ Source or Header  |  2001-12-16  |  2KB  |  77 lines

  1. #include "syshdrs.h"
  2. #ifdef PRAGMA_HDRSTOP
  3. #    pragma hdrstop
  4. #endif
  5.  
  6. /* Use Dynscpy when you want to manage free'ing the created pointer
  7.  * yourself; Dynsrecpy will try to free an existing pointer if needed
  8.  * before creating the new string, but you have to be sure to be sure
  9.  * initialize the pointer to NULL the first time you use it..
  10.  *
  11.  * Example:
  12.  *
  13.  * {
  14.  *     char *p;                            -* p contains garbage *-
  15.  *     Dynscpy(&p, "foo", "bar", 0);       -* no need to initialize p *-
  16.  *     free(p);                            -* must free p to avoid leak *-
  17.  *     Dynscpy(&p, "hello", "world", 0);   -* p can now be reused *-
  18.  *     free(p);                            -* must free p to avoid leak *-
  19.  *     Dynscpy(&p, "test", "123", 0);      -* p can now be reused *-
  20.  *     free(p);                            -* free p when finished *-
  21.  * }
  22.  *
  23.  * {
  24.  *     char *p;
  25.  *     p = NULL;  -* Must init p to NULL, else free() will get garbage *-
  26.  *     Dynsrecpy(&p, "foo", "bar", 0);     -* on this call to Dynsrecpy *-
  27.  *     Dynsrecpy(&p, "hello", "world", 0); -* p will be freed *-
  28.  *     Dynsrecpy(&p, "test", "123", 0);    -* p will be freed *-
  29.  *     free(p);                            -* free p when finished *-
  30.  * }
  31.  */
  32.  
  33. /*VARARGS*/
  34. char *
  35. Dynscpy(char **dst, ...)
  36. {
  37.     va_list ap;
  38.     const char *src;
  39.     char *newdst, *dcp;
  40.     size_t curLen, catLen, srcLen;
  41.  
  42.     if (dst == (char **) 0)
  43.         return NULL;
  44.  
  45.     catLen = 0;
  46.     va_start(ap, dst);
  47.     src = va_arg(ap, char *);
  48.     while (src != NULL) {
  49.         catLen += strlen(src);
  50.         src = va_arg(ap, char *);
  51.     }
  52.     va_end(ap);
  53.  
  54.     curLen = 0;
  55.  
  56.     newdst = malloc(curLen + catLen + 2);
  57.     if (newdst == NULL) {
  58.         *dst = NULL;
  59.         return NULL;
  60.     }
  61.  
  62.     dcp = newdst + curLen;
  63.     va_start(ap, dst);
  64.     src = va_arg(ap, char *);
  65.     while (src != NULL) {
  66.         srcLen = strlen(src);
  67.         memcpy(dcp, src, srcLen);
  68.         dcp += srcLen;
  69.         src = va_arg(ap, char *);
  70.     }
  71.     va_end(ap);
  72.     *dcp = '\0';
  73.  
  74.     *dst = newdst;
  75.     return (newdst);
  76. }    /* Dynscpy */
  77.