Format data and automatically allocate memory to be of sufficient length.
This is a care-free alternative to snprintf() with strings of arbitrary length.
char *buf = maprintf( "%s: %s", key, value );
/* do something with buf */
free( buf );
#include <stdio.h> | |
#include <stdlib.h> | |
#include <stdarg.h> | |
#include "maprintf.h" | |
/** | |
* Format data and automatically allocate memory to be of sufficient length | |
* | |
* @param format - printf format description | |
* @param ... - arguments | |
*/ | |
char *maprintf( const char *format, ... ) | |
{ | |
va_list ap; | |
char *buf; | |
int len; | |
int req; | |
va_start( ap, format ); | |
len = vsnprintf( NULL, 0, format, ap ); | |
va_end( ap ); | |
if( len < 1 || | |
!(buf = (char *)calloc( ++len, sizeof( char ) )) ) | |
return NULL; | |
va_start( ap, format ); | |
req = vsnprintf( buf, len, format, ap ); | |
va_end( ap ); | |
if( req < 0 || | |
req >= len ) | |
{ | |
free( buf ); | |
return NULL; | |
} | |
return buf; | |
} |
#ifndef _maprintf_h_ | |
#define _maprintf_h_ | |
char *maprintf( const char *, ... ); | |
#endif |