dcc9cd81cc8879c94d5d2ca810c993c9c8376cf8
[citadel.git] / citadel / snprintf.c
1 /*
2  * $Id$
3  *
4  * Replacements for snprintf() and vsnprintf()
5  *
6  * modified from Sten Gunterberg's BUGTRAQ post of 22 Jul 1997
7  * --nathan bryant <nathan@designtrust.com>
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 vsnprintf (char *buf, size_t max, const char *fmt, va_list argp)
51 {
52   char *p;
53   int size;
54
55   if ((p = malloc(needed(fmt, argp) + 1)) == NULL)
56     {
57       fprintf(stderr, "vsnprintf: malloc failed, aborting\n");
58       abort();
59     }
60
61   if ((size = vsprintf(p, fmt, argp)) >= max)
62     size = -1;
63
64   strncpy(buf, p, max);
65   buf[max - 1] = 0;
66   free(p);
67   return size;
68 }
69
70 int
71 snprintf (char *buf, size_t max, const char *fmt, ...)
72 {
73   va_list argp;
74   int bytes;
75
76   va_start(argp, fmt);
77   bytes = vsnprintf(buf, max, fmt, argp);
78   va_end(argp);
79
80   return bytes;
81 }