* snprintf.c, snprintf.h: new files
[citadel.git] / citadel / snprintf.c
1 /*
2  * modified from Sten Gunterberg's BUGTRAQ post of 22 Jul 1997
3  * --nathan bryant <bryant@cs.usm.maine.edu>
4  */
5
6 /*
7  * Replacements for snprintf() and vsnprintf()
8  *
9  * Use it only if you have the "spare" cycles needed to effectively
10  * do every snprintf operation twice! Why is that? Because everything
11  * is first vfprintf()'d to /dev/null to determine the number of bytes.
12  * Perhaps a bit slow for demanding applications on slow machines,
13  * no problem for a fast machine with some spare cycles.
14  *
15  * You don't have a /dev/null? Every Linux contains one for free!
16  *
17  * Because the format string is never even looked at, all current and
18  * possible future printf-conversions should be handled just fine.
19  *
20  * Written July 1997 by Sten Gunterberg (gunterberg@ergon.ch)
21  */
22
23 #include <stdio.h>
24 #include <stdlib.h>
25 #include <stdarg.h>
26 #include <string.h>
27
28 static int
29 needed (const char *fmt, va_list argp)
30 {
31   static FILE *sink = NULL;
32
33   /* ok, there's a small race here that could result in the sink being
34    * opened more than once if we're threaded, but I'd rather ignore it than
35    * spend cycles synchronizing :-) */
36
37   if (sink == NULL)
38     {
39       if ((sink = fopen("/dev/null", "w")) == NULL)
40         {
41           perror("/dev/null");
42           exit(1);
43         }
44     }
45
46   return vfprintf(sink, fmt, argp);
47 }
48
49 int
50 snprintf (char *buf, size_t max, const char *fmt, ...)
51 {
52   va_list argp;
53   int bytes;
54
55   va_start(argp, fmt);
56   bytes = vsnprintf(buf, max, fmt, argp);
57   va_end(argp);
58
59   return bytes;
60 }
61
62 int
63 vsnprintf (char *buf, size_t max, const char *fmt, va_list argp)
64 {
65   char *p;
66   int size;
67
68   if ((p = malloc(needed(fmt, argp) + 1)) == NULL)
69     {
70       fprintf(stderr, "vsnprintf: malloc failed, aborting\n");
71       abort();
72     }
73
74   if ((size = vsprintf(p, fmt, argp)) >= max)
75     size = -1;
76
77   strncpy(buf, p, max);
78   buf[max - 1] = 0;
79   free(p);
80   return size;
81 }