home *** CD-ROM | disk | FTP | other *** search
- #include <stdarg.h>
- #include <stdlib.h>
- #include <assert.h>
- #include <stdio.h>
- #include <ctype.h>
- #include <string.h>
- #include "StringUtils.h"
- #include "xmalloc.h"
-
- /* Print to a memory buffer and allocate a larger one as needed.
- If return is != buf, we allocated, and the caller must free. */
- char *
- mvprintf(char *mybuf, unsigned len, const char *format, va_list va)
- {
- int maxlen;
- int ret;
- char *buf;
-
- assert(mybuf != NULL);
- maxlen = len;
- buf = mybuf;
-
- /* return of -1 indicates buffer is in old standards;
- return of val >= maxlen indicates buffer is too small in C9X */
- ret = vsnprintf(buf, maxlen, format, va);
- if (ret < 0) {
- do {
- if (buf != mybuf)
- free(buf);
- maxlen <<= 1;
- //if (maxlen >= 65536) /* prolly an error */
- // return NULL;
- buf = (char *) xmalloc(maxlen);
- } while ((ret = vsnprintf(buf, maxlen, format, va)) < 0);
- } else if (ret > maxlen) {
- maxlen = ret + 1;
- buf = (char *) xmalloc(maxlen);
- ret = vsnprintf(buf, maxlen, format, va);
- }
-
- return buf;
- }
-
- char *
- mprintf(char *mybuf, unsigned len, const char *format, ...)
- {
- va_list va;
- char *ret;
-
- va_start(va, format);
- ret = mvprintf(mybuf, len, format, va);
- va_end(va);
-
- return ret;
- }
-