2 * Replacements for snprintf() and vsnprintf()
4 * modified from Sten Gunterberg's BUGTRAQ post of 22 Jul 1997
5 * --nathan bryant <nathan@designtrust.com>
7 * Use it only if you have the "spare" cycles needed to effectively
8 * do every snprintf operation twice! Why is that? Because everything
9 * is first vfprintf()'d to /dev/null to determine the number of bytes.
10 * Perhaps a bit slow for demanding applications on slow machines,
11 * no problem for a fast machine with some spare cycles.
13 * You don't have a /dev/null? Every Linux contains one for free!
15 * Because the format string is never even looked at, all current and
16 * possible future printf-conversions should be handled just fine.
18 * Written July 1997 by Sten Gunterberg (gunterberg@ergon.ch)
27 needed (const char *fmt, va_list argp)
29 static FILE *sink = NULL;
31 /* ok, there's a small race here that could result in the sink being
32 * opened more than once if we're threaded, but I'd rather ignore it than
33 * spend cycles synchronizing :-) */
37 if ((sink = fopen("/dev/null", "w")) == NULL)
44 return vfprintf(sink, fmt, argp);
48 vsnprintf (char *buf, size_t max, const char *fmt, va_list argp)
53 if ((p = malloc(needed(fmt, argp) + 1)) == NULL)
55 fprintf(stderr, "vsnprintf: malloc failed, aborting\n");
59 if ((size = vsprintf(p, fmt, argp)) >= max)
69 snprintf (char *buf, size_t max, const char *fmt, ...)
75 bytes = vsnprintf(buf, max, fmt, argp);