47 lines
1.0 KiB
C
47 lines
1.0 KiB
C
#include "util.h"
|
|
#include <stdio.h>
|
|
#include <stdlib.h>
|
|
#include <string.h>
|
|
#include <stdarg.h>
|
|
|
|
/* Portable va_copy fallback for pre-C99 or platforms without va_copy. */
|
|
#ifndef va_copy
|
|
# if defined(__va_copy)
|
|
# define va_copy(dest, src) __va_copy(dest, src)
|
|
# else
|
|
# define va_copy(dest, src) ((dest) = (src))
|
|
# endif
|
|
#endif
|
|
|
|
char* format_string_va(const char* fmt, va_list args) {
|
|
/* Declarations first to satisfy -std=c89 */
|
|
va_list args_copy;
|
|
int needed;
|
|
char* buf;
|
|
|
|
if (!fmt) return NULL;
|
|
|
|
va_copy(args_copy, args);
|
|
needed = vsnprintf(NULL, 0, fmt, args_copy);
|
|
va_end(args_copy);
|
|
if (needed < 0) return NULL;
|
|
|
|
buf = (char*)malloc((size_t)needed + 1);
|
|
if (!buf) return NULL;
|
|
vsnprintf(buf, (size_t)needed + 1, fmt, args);
|
|
return buf;
|
|
}
|
|
|
|
char* format_string(const char* fmt, ...) {
|
|
/* Declarations first to satisfy -std=c89 */
|
|
va_list args;
|
|
char* s;
|
|
|
|
if (!fmt) return NULL;
|
|
|
|
va_start(args, fmt);
|
|
s = format_string_va(fmt, args);
|
|
va_end(args);
|
|
return s;
|
|
}
|