From f60033cf04deb2019320ebb5ac7deebb16818703 Mon Sep 17 00:00:00 2001 From: Ben Date: Tue, 18 Feb 2014 23:01:34 -0500 Subject: [PATCH] Add asprintf.c --- asprintf.c | 49 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) create mode 100644 asprintf.c diff --git a/asprintf.c b/asprintf.c new file mode 100644 index 0000000..2e5b6fb --- /dev/null +++ b/asprintf.c @@ -0,0 +1,49 @@ +#ifndef HAVE_ASPRINTF +#include //vsnprintf +#include //malloc +#include //va_start et al + +/* The declaration, to put into a .h file. The __attribute___ tells the compiler to check printf-style type-compliance. + It's not C standard, but a lot of compilers supprt it. Just remove it if yours doesn't */ + +int asprintf(char **str, char* fmt, ...) __attribute__ ((format (printf,2,3))); + + +int asprintf(char **str, char* fmt, ...){ + va_list argp; + va_start(argp, fmt); + char one_char[1]; + int len = vsnprintf(one_char, 1, fmt, argp); + if (len < 1){ + fprintf(stderr, "An encoding error occurred. Setting the input pointer to NULL.\n"); + *str = NULL; + return len; + } + va_end(argp); + + *str = malloc(len+1); + if (!str) { + fprintf(stderr, "Couldn't allocate %i bytes.\n", len+1); + return -1; + } + va_start(argp, fmt); + vsnprintf(*str, len+1, fmt, argp); + va_end(argp); + return len; +} +#endif + +#ifdef Test_asprintf +int main(){ + char *s; + asprintf(&s, "hello, %s.", "—Reader—"); + printf("%s\n", s); + + asprintf(&s, "%c", '\0'); + printf("blank string: [%s]\n", s); + + int i = 0; + asprintf(&s, "%i", i++); + printf("Zero: %s\n", s); +} +#endif -- GitLab