util: c++ version of sprintf
authorRobert Swiecki <robert@swiecki.net>
Sat, 16 Jun 2018 00:16:24 +0000 (02:16 +0200)
committerRobert Swiecki <robert@swiecki.net>
Sat, 16 Jun 2018 00:16:24 +0000 (02:16 +0200)
util.cc
util.h

diff --git a/util.cc b/util.cc
index 87a9332..ddf39b8 100644 (file)
--- a/util.cc
+++ b/util.cc
@@ -176,6 +176,24 @@ std::string* StrAppend(std::string* str, const char* format, ...) {
        return str;
 }
 
+std::string StrPrintf(const char* format, ...) {
+       char* strp;
+
+       va_list args;
+       va_start(args, format);
+       int ret = vasprintf(&strp, format, args);
+       va_end(args);
+
+       if (ret == -1) {
+               PLOG_E("Memory allocation failed during asprintf()");
+               return "[ERROR: mem_allocation_failed]";
+       }
+
+       std::string str(strp, ret);
+       free(strp);
+       return str;
+}
+
 bool isANumber(const char* s) {
        for (size_t i = 0; s[i]; s++) {
                if (!isdigit(s[i]) && s[i] != 'x') {
diff --git a/util.h b/util.h
index f843837..3bf71a5 100644 (file)
--- a/util.h
+++ b/util.h
@@ -40,6 +40,7 @@ bool writeBufToFile(const char* filename, const void* buf, size_t len, int open_
 bool createDirRecursively(const char* dir);
 std::string* StrAppend(std::string* str, const char* format, ...)
     __attribute__((format(printf, 2, 3)));
+std::string StrPrintf(const char* format, ...) __attribute__((format(printf, 1, 2)));
 bool isANumber(const char* s);
 uint64_t rnd64(void);
 const std::string sigName(int signo);