vasprintf的实现

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

代码如下:

 

 1 #if !defined(HAVE_VASPRINTF) 
 2 #if defined(WINDOWS) 
 3 int 
 4 vasprintf (char **ptr, const char *format, va_list ap) 
 5 { 
 6   int len; 
 7  
 8   len = _vscprintf_p (format, ap) + 1; 
 9   *ptr = (char *) malloc (len * sizeof (char)); 
10   if (!*ptr) 
11     { 
12       return -1; 
13     } 
14  
15   return _vsprintf_p (*ptr, len, format, ap); 
16 } 
17 #else 
18 int 
19 vasprintf (char **ptr, const char *format, va_list ap) 
20 { 
21   va_list ap_copy; 
22  
23   /* Make sure it is determinate, despite manuals indicating otherwise */ 
24   *ptr = 0; 
25  
26   va_copy(ap_copy, ap); 
27   int count = vsnprintf(NULL, 0, format, ap); 
28   if (count >= 0) 
29         { 
30           char* buffer = malloc(count + 1); 
31           if (buffer != NULL) 
32                 { 
33                   count = vsnprintf(buffer, count + 1, format, ap_copy); 
34                   if (count < 0) 
35                         free(buffer); 
36                   else 
37                         *ptr = buffer; 
38                 } 
39         } 
40   va_end(ap_copy); 
41  
42   return count; 
43  
44 } 
45 #endif 
46 #endif /* !HAVE_VASPRINTF */ 
47  
48 #if !defined(HAVE_ASPRINTF) 
49 int 
50 asprintf (char **ptr, const char *format, ...) 
51 { 
52   va_list ap; 
53   int ret; 
54  
55   *ptr = NULL; 
56  
57   va_start (ap, format); 
58   ret = vasprintf (ptr, format, ap); 
59   va_end (ap); 
60  
61   return ret; 
62 } 
63 #endif /* !HAVE_ASPRINTF */ 

 

下面是一个完整的例子:

 

 1 #include <stdio.h> 
 2 #include <stdarg.h> 
 3 #include <stdlib.h> 
 4 #include <string.h> 
 5  
 6 int 
 7 myvasprintf (char **ptr, const char *format, va_list ap) 
 8 { 
 9   va_list ap_copy; 
10  
11   /* Make sure it is determinate, despite manuals indicating otherwise */ 
12   *ptr = 0; 
13  
14   va_copy(ap_copy, ap); 
15   int count = vsnprintf(NULL, 0, format, ap); 
16   if (count >= 0) 
17     { 
18       char* buffer = malloc(count + 1); 
19       if (buffer != NULL) 
20         { 
21           count = vsnprintf(buffer, count + 1, format, ap_copy); 
22           if (count < 0) 
23             free(buffer); 
24           else 
25             *ptr = buffer; 
26         } 
27     } 
28   va_end(ap_copy); 
29  
30   return count; 
31  
32 } 
33  
34 void 
35 print_warning (char **buffer, const char *fmt, ...) 
36 { 
37   va_list ap; 
38   va_start (ap, fmt); 
39   myvasprintf (buffer, fmt, ap); 
40   va_end (ap); 
41 } 
42  
43 int main() 
44 { 
45   char *buffer; 
46   int a = 99999; 
47   int b = 9; 
48   print_warning(&buffer, "hello, world, %d * %d = %d, %s\n", a, b, a * b, "finished!!" ); 
49  
50   printf(buffer); 
51   return 0; 
52 } 

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

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

 

posted @ 2013-09-27 11:51  laughingLau  阅读(3807)  评论(0编辑  收藏  举报