* Fixed an error in the template that was causing the 'c_creataide' field to load...
[citadel.git] / citadel / snprintf.c
blobdcc9cd81cc8879c94d5d2ca810c993c9c8376cf8
1 /*
2 * $Id$
4 * Replacements for snprintf() and vsnprintf()
6 * modified from Sten Gunterberg's BUGTRAQ post of 22 Jul 1997
7 * --nathan bryant <nathan@designtrust.com>
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.
15 * You don't have a /dev/null? Every Linux contains one for free!
17 * Because the format string is never even looked at, all current and
18 * possible future printf-conversions should be handled just fine.
20 * Written July 1997 by Sten Gunterberg (gunterberg@ergon.ch)
23 #include <stdio.h>
24 #include <stdlib.h>
25 #include <stdarg.h>
26 #include <string.h>
28 static int
29 needed (const char *fmt, va_list argp)
31 static FILE *sink = NULL;
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 :-) */
37 if (sink == NULL)
39 if ((sink = fopen("/dev/null", "w")) == NULL)
41 perror("/dev/null");
42 exit(1);
46 return vfprintf(sink, fmt, argp);
49 int
50 vsnprintf (char *buf, size_t max, const char *fmt, va_list argp)
52 char *p;
53 int size;
55 if ((p = malloc(needed(fmt, argp) + 1)) == NULL)
57 fprintf(stderr, "vsnprintf: malloc failed, aborting\n");
58 abort();
61 if ((size = vsprintf(p, fmt, argp)) >= max)
62 size = -1;
64 strncpy(buf, p, max);
65 buf[max - 1] = 0;
66 free(p);
67 return size;
70 int
71 snprintf (char *buf, size_t max, const char *fmt, ...)
73 va_list argp;
74 int bytes;
76 va_start(argp, fmt);
77 bytes = vsnprintf(buf, max, fmt, argp);
78 va_end(argp);
80 return bytes;