有些系统,例如AIX,没有vasprintf和asprintf ,如果是做porting,有时需要写一个简单的代替。

代码如下:

 #if !defined(HAVE_VASPRINTF)
#if defined(WINDOWS)
int
vasprintf (char **ptr, const char *format, va_list ap)
{
int len; len = _vscprintf_p (format, ap) + ;
*ptr = (char *) malloc (len * sizeof (char));
if (!*ptr)
{
return -;
} return _vsprintf_p (*ptr, len, format, ap);
}
#else
int
vasprintf (char **ptr, const char *format, va_list ap)
{
va_list ap_copy; /* Make sure it is determinate, despite manuals indicating otherwise */
*ptr = ; va_copy(ap_copy, ap);
int count = vsnprintf(NULL, , format, ap);
if (count >= )
{
char* buffer = malloc(count + );
if (buffer != NULL)
{
count = vsnprintf(buffer, count + , format, ap_copy);
if (count < )
free(buffer);
else
*ptr = buffer;
}
}
va_end(ap_copy); return count; }
#endif
#endif /* !HAVE_VASPRINTF */ #if !defined(HAVE_ASPRINTF)
int
asprintf (char **ptr, const char *format, ...)
{
va_list ap;
int ret; *ptr = NULL; va_start (ap, format);
ret = vasprintf (ptr, format, ap);
va_end (ap); return ret;
}
#endif /* !HAVE_ASPRINTF */
下面是一个完整的例子:
 #include <stdio.h>
#include <stdarg.h>
#include <stdlib.h>
#include <string.h> int
myvasprintf (char **ptr, const char *format, va_list ap)
{
va_list ap_copy; /* Make sure it is determinate, despite manuals indicating otherwise */
*ptr = ; va_copy(ap_copy, ap);
int count = vsnprintf(NULL, , format, ap);
if (count >= )
{
char* buffer = malloc(count + );
if (buffer != NULL)
{
count = vsnprintf(buffer, count + , format, ap_copy);
if (count < )
free(buffer);
else
*ptr = buffer;
}
}
va_end(ap_copy); return count; } void
print_warning (char **buffer, const char *fmt, ...)
{
va_list ap;
va_start (ap, fmt);
myvasprintf (buffer, fmt, ap);
va_end (ap);
} int main()
{
char *buffer;
int a = ;
int b = ;
print_warning(&buffer, "hello, world, %d * %d = %d, %s\n", a, b, a * b, "finished!!" ); printf(buffer);
return ;
}

上述代码的执行结果如下:

hello, world, 99999 * 9 = 899991, finished!!

04-30 01:29