From: Michael Elkins Date: Sun, 8 Aug 2010 17:40:38 +0000 (-0700) Subject: add a malloc+sprintf combo function X-Git-Url: https://granicus.if.org/sourcecode?a=commitdiff_plain;h=9b1cf33b613b3b61ccd10f30773b34c6dda56af2;p=mutt add a malloc+sprintf combo function --- diff --git a/lib.c b/lib.c index 17cc5160..0d829154 100644 --- a/lib.c +++ b/lib.c @@ -1082,3 +1082,34 @@ int mutt_atol (const char *str, long *dst) return -1; return 0; } + +/* Allocate a C-string large enough to contain the formatted string. + * This is essentially malloc+sprintf in one. + */ +char *mutt_sprintf (const char *fmt, ...) +{ + size_t rlen = STRING; + char *r = safe_malloc (rlen); + for (;;) + { + va_list ap; + va_start (ap, fmt); + size_t n = vsnprintf (r, rlen, fmt, ap); + va_end (ap); + if (n < rlen) + { + /* reduce space to just that which was used. note that 'n' does not + * include the terminal nul char. + */ + if (n == 0) /* convention is to use NULL for zero-length strings. */ + FREE (&r); + else if (n != rlen - 1) + safe_realloc (&r, n + 1); + return r; + } + /* increase size and try again */ + rlen = n + 1; + safe_realloc(&r, rlen); + } + /* not reached */ +} diff --git a/lib.h b/lib.h index e13e1a24..b08f909d 100644 --- a/lib.h +++ b/lib.h @@ -153,6 +153,7 @@ char *mutt_concatn_path (char *, size_t, const char *, size_t, const char *, siz char *mutt_concat_path (char *, const char *, const char *, size_t); char *mutt_read_line (char *, size_t *, FILE *, int *, int); char *mutt_skip_whitespace (char *); +char *mutt_sprintf (const char *, ...); char *mutt_strlower (char *); char *mutt_substrcpy (char *, const char *, const char *, size_t); char *mutt_substrdup (const char *, const char *);