1 /* Like vsprintf but provides a pointer to malloc'd storage, which must
2 be freed by the caller.
3 Copyright (C) 1994 Free Software Foundation, Inc.
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation; either version 2, or (at your option)
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with this program; if not, write to the Free Software
17 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */
34 int global_total_width;
37 /* unsigned long strtoul (); */
38 /* char *malloc (); */
41 int_vasprintf (result, format, args)
46 const char *p = format;
47 /* Add one to make sure that it is never zero, which might cause malloc
49 int total_width = strlen (format) + 1;
52 memcpy (&ap, args, sizeof (va_list));
58 while (strchr ("-+ #0", *p))
63 total_width += abs (va_arg (ap, int));
66 total_width += strtoul (p, &p, 10);
73 total_width += abs (va_arg (ap, int));
76 total_width += strtoul (p, &p, 10);
78 while (strchr ("hlL", *p))
80 /* Should be big enough for any format specifier except %s. */
91 (void) va_arg (ap, int);
98 (void) va_arg (ap, double);
101 total_width += strlen (va_arg (ap, char *));
105 (void) va_arg (ap, char *);
111 global_total_width = total_width;
113 *result = malloc (total_width);
115 return vsprintf (*result, format, *args);
121 vasprintf (result, format, args)
126 return int_vasprintf (result, format, &args);
132 (char **result, const char *format, ...)
143 va_start (args, format);
147 format = va_arg (args, char *);
149 done = vasprintf (result, format, args);
159 (const char* format, ...)
169 va_start (args, format);
173 format = va_arg (args, char *);
175 vasprintf (&result, format, args);
176 if (strlen (result) < global_total_width)
180 printf ("%d %s\n", global_total_width, result);
186 checkit ("%d", 0x12345678);
187 checkit ("%200d", 5);
188 checkit ("%.300d", 6);
189 checkit ("%100.150d", 7);
190 checkit ("%s", "jjjjjjjjjiiiiiiiiiiiiiiioooooooooooooooooppppppppppppaa\n\
191 777777777777777777333333333333366666666666622222222222777777777777733333");
192 checkit ("%f%s%d%s", 1.0, "foo", 77, "asdjffffffffffffffiiiiiiiiiiixxxxx");