有些系统,例如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) + 1;
- *ptr = (char *) malloc (len * sizeof (char));
- if (!*ptr)
- {
- return -1;
- }
- 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 = 0;
- va_copy(ap_copy, ap);
- int count = vsnprintf(NULL, 0, format, ap);
- if (count >= 0)
- {
- char* buffer = malloc(count + 1);
- if (buffer != NULL)
- {
- count = vsnprintf(buffer, count + 1, format, ap_copy);
- if (count < 0)
- 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 = 0;
- va_copy(ap_copy, ap);
- int count = vsnprintf(NULL, 0, format, ap);
- if (count >= 0)
- {
- char* buffer = malloc(count + 1);
- if (buffer != NULL)
- {
- count = vsnprintf(buffer, count + 1, format, ap_copy);
- if (count < 0)
- 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 = 99999;
- int b = 9;
- print_warning(&buffer, "hello, world, %d * %d = %d, %s\n", a, b, a * b, "finished!!" );
- printf(buffer);
- return 0;
- }
上述代码的执行结果如下:
hello, world, 99999 * 9 = 899991, finished!!
转载于:https://blog.51cto.com/leander/1151729