diff options
author | Michael Elkins <me@sigpipe.org> | 2010-08-08 10:40:38 -0700 |
---|---|---|
committer | Michael Elkins <me@sigpipe.org> | 2010-08-08 10:40:38 -0700 |
commit | 9b1cf33b613b3b61ccd10f30773b34c6dda56af2 (patch) | |
tree | 5aa8b24629b0839c9abc9c81399ddf3eaef22cfd | |
parent | 306406f6713c22e6c9e82cc533f9255f379af5f4 (diff) |
add a malloc+sprintf combo function
-rw-r--r-- | lib.c | 31 | ||||
-rw-r--r-- | lib.h | 1 |
2 files changed, 32 insertions, 0 deletions
@@ -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 */ +} @@ -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 *); |