home *** CD-ROM | disk | FTP | other *** search
/ ftp.whtech.com / ftp.whtech.com.7z / ftp.whtech.com / emulators / v9t9 / linux / sources / V9t9 / source / OSLib / StringUtils.c < prev    next >
Encoding:
C/C++ Source or Header  |  2006-10-19  |  1.2 KB  |  56 lines

  1. #include <stdarg.h>
  2. #include <stdlib.h>
  3. #include <assert.h>
  4. #include <stdio.h>
  5. #include <ctype.h>
  6. #include <string.h>
  7. #include "StringUtils.h"
  8. #include "xmalloc.h"
  9.  
  10. /*    Print to a memory buffer and allocate a larger one as needed.
  11.     If return is != buf, we allocated, and the caller must free. */
  12. char       *
  13. mvprintf(char *mybuf, unsigned len, const char *format, va_list va)
  14. {
  15.     int         maxlen;
  16.     int         ret;
  17.     char       *buf;
  18.  
  19.     assert(mybuf != NULL);
  20.     maxlen = len;
  21.     buf = mybuf;
  22.  
  23.     /*  return of -1 indicates buffer is in old standards;
  24.        return of val >= maxlen indicates buffer is too small in C9X */
  25.     ret = vsnprintf(buf, maxlen, format, va);
  26.     if (ret < 0) {
  27.         do {
  28.             if (buf != mybuf)
  29.                 free(buf);
  30.             maxlen <<= 1;
  31.             //if (maxlen >= 65536)      /* prolly an error */
  32.             //  return NULL;
  33.             buf = (char *) xmalloc(maxlen);
  34.         } while ((ret = vsnprintf(buf, maxlen, format, va)) < 0);
  35.     } else if (ret > maxlen) {
  36.         maxlen = ret + 1;
  37.         buf = (char *) xmalloc(maxlen);
  38.         ret = vsnprintf(buf, maxlen, format, va);
  39.     }
  40.  
  41.     return buf;
  42. }
  43.  
  44. char       *
  45. mprintf(char *mybuf, unsigned len, const char *format, ...)
  46. {
  47.     va_list     va;
  48.     char       *ret;
  49.  
  50.     va_start(va, format);
  51.     ret = mvprintf(mybuf, len, format, va);
  52.     va_end(va);
  53.  
  54.     return ret;
  55. }
  56.