You can use a strbuf to build up a string from parts, and then detach it. In the general case, you might use multiple strbuf_add* functions to do the building. However, in many cases, a single strbuf_addf is sufficient, and we end up with: struct strbuf buf = STRBUF_INIT; ... strbuf_addf(&buf, fmt, some, args); str = strbuf_detach(&buf, NULL); We can make this much more readable (and avoid introducing an extra variable, which can clutter the code) by introducing a convenience function: str = xstrdup_fmt(fmt, some, args); Signed-off-by: Jeff King <peff@xxxxxxxx> --- I'm open to suggestions on the name. This really is the same thing conceptually as the GNU asprintf(), but the interface is different (that function takes a pointer-to-pointer as an out-parameter, and returns the number of characters return). strbuf.c | 19 +++++++++++++++++++ strbuf.h | 9 +++++++++ 2 files changed, 28 insertions(+) diff --git a/strbuf.c b/strbuf.c index ac62982..6674d74 100644 --- a/strbuf.c +++ b/strbuf.c @@ -600,3 +600,22 @@ char *xstrdup_tolower(const char *string) result[i] = '\0'; return result; } + +char *xstrdup_vfmt(const char *fmt, va_list ap) +{ + struct strbuf buf = STRBUF_INIT; + strbuf_vaddf(&buf, fmt, ap); + return strbuf_detach(&buf, NULL); +} + +char *xstrdup_fmt(const char *fmt, ...) +{ + va_list ap; + char *ret; + + va_start(ap, fmt); + ret = xstrdup_vfmt(fmt, ap); + va_end(ap); + + return ret; +} diff --git a/strbuf.h b/strbuf.h index e9ad03e..61818f9 100644 --- a/strbuf.h +++ b/strbuf.h @@ -187,4 +187,13 @@ extern int fprintf_ln(FILE *fp, const char *fmt, ...); char *xstrdup_tolower(const char *); +/* + * Create a newly allocated string using printf format. You can do this easily + * with a strbuf, but this provides a shortcut to save a few lines. + */ +__attribute__((format (printf, 1, 0))) +char *xstrdup_vfmt(const char *fmt, va_list ap); +__attribute__((format (printf, 1, 2))) +char *xstrdup_fmt(const char *fmt, ...); + #endif /* STRBUF_H */ -- 2.0.0.566.gfe3e6b2 -- To unsubscribe from this list: send the line "unsubscribe git" in the body of a message to majordomo@xxxxxxxxxxxxxxx More majordomo info at http://vger.kernel.org/majordomo-info.html