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