treewrite: use Lindent to reformat to kernel coding style
[oweals/opkg-lede.git] / libopkg / sprintf_alloc.c
1 /* sprintf_alloc.c -- like sprintf with memory allocation
2
3    Copyright (C) 2010 Ubiq Technologies <graham.gower@gmail.com>
4
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)
8    any later version.
9
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.
14 */
15
16 #include <stdarg.h>
17
18 #include "sprintf_alloc.h"
19 #include "libbb/libbb.h"
20
21 void sprintf_alloc(char **str, const char *fmt, ...)
22 {
23         va_list ap;
24         int n;
25         unsigned int size = 0;
26
27         *str = NULL;
28
29         for (;;) {
30                 va_start(ap, fmt);
31                 n = vsnprintf(*str, size, fmt, ap);
32                 va_end(ap);
33
34                 if (n < 0) {
35                         fprintf(stderr, "%s: encountered an output or encoding"
36                                 " error during vsnprintf.\n", __FUNCTION__);
37                         exit(EXIT_FAILURE);
38                 }
39
40                 if (n < size)
41                         break;
42
43                 /* Truncated, try again with more space. */
44                 size = n + 1;
45                 *str = xrealloc(*str, size);
46         }
47 }