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)
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 :-) */
39 if ((sink
= fopen("/dev/null", "w")) == NULL
)
46 return vfprintf(sink
, fmt
, argp
);
50 vsnprintf (char *buf
, size_t max
, const char *fmt
, va_list argp
)
55 if ((p
= malloc(needed(fmt
, argp
) + 1)) == NULL
)
57 fprintf(stderr
, "vsnprintf: malloc failed, aborting\n");
61 if ((size
= vsprintf(p
, fmt
, argp
)) >= max
)
71 snprintf (char *buf
, size_t max
, const char *fmt
, ...)
77 bytes
= vsnprintf(buf
, max
, fmt
, argp
);