From c3c5d00fa12281fcf80156d040e471fdc9123aac Mon Sep 17 00:00:00 2001 From: andreymuch Date: Sat, 25 May 2024 17:05:31 +0300 Subject: [PATCH] Implementation of stringFormat function --- cstring.h | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/cstring.h b/cstring.h index 1a76fc5..b8cc547 100644 --- a/cstring.h +++ b/cstring.h @@ -6,6 +6,7 @@ #include #include #include +#include typedef enum EErrorCode { ERR_NO_ERROR, @@ -609,6 +610,34 @@ TString stringSubstring(TString s, size_t pos, size_t len) { return res; } +TString stringFormat(const char* format, ...) { + va_list args; + va_start(args, format); + va_list args_copy; + va_copy(args_copy, args); + const int size = vsnprintf(NULL, 0, format, args_copy); + va_end(args_copy); + if (size < 0) { + const TString error_result = { NULL, 0, 0 }; + va_end(args); + return error_result; + } + TString result; + result.size = size; + result.capacity = size + 1; + result.data = (char*)malloc(result.capacity); + + if (!result.data) { + result.size = 0; + result.capacity = 0; + va_end(args); + return result; + } + vsnprintf(result.data, result.capacity, format, args); + va_end(args); + return result; +} + void stringScan(TString *s) { if (s == NULL) { setError(ERR_NULL_POINTER);