6 * Replacements for snprintf() and vsnprintf()
8 * Use it only if you have the "spare" cycles needed to effectively
9 * do every snprintf operation twice! Why is that? Because everything
10 * is first vfprintf()'d to /dev/null to determine the number of bytes.
11 * Perhaps a bit slow for demanding applications on slow machines,
12 * no problem for a fast machine with some spare cycles.
14 * You don't have a /dev/null? Every Linux contains one for free!
16 * Because the format string is never even looked at, all current and
17 * possible future printf-conversions should be handled just fine.
19 * Written July 1997 by Sten Gunterberg (gunterberg@ergon.ch)
23 #include "webserver.h"
27 * fmt the formatstring?
28 * argp how many params?
30 static int needed(const char *fmt
, va_list argp
)
32 static FILE *sink
= NULL
;
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 :-) */
40 if ((sink
= fopen("/dev/null", "w")) == NULL
) {
45 return vfprintf(sink
, fmt
, argp
);
50 * buf the output charbuffer
51 * max maximal size of the buffer
52 * fmt the formatstring (see man printf)
53 * argp the variable argument list
55 int vsnprintf(char *buf
, size_t max
, const char *fmt
, va_list argp
)
60 if ((p
= malloc(needed(fmt
, argp
) + 1)) == NULL
) {
61 lprintf(1, "vsnprintf: malloc failed, aborting\n");
64 if ((size
= vsprintf(p
, fmt
, argp
)) >= max
)
75 * buf the output charbuffer
76 * max maximal size of the buffer
77 * fmt the formatstring (see man printf)
78 * ... the variable argument list
80 int snprintf(char *buf
, size_t max
, const char *fmt
,...)
86 bytes
= vsnprintf(buf
, max
, fmt
, argp
);