citadel
About: Citadel is an advanced messaging and collaboration system for groupware and BBS applications (preferred OS: Linux).
  Fossies Dox: citadel.tar.gz  ("unofficial" and yet experimental doxygen-generated source code documentation)  

snprintf.c
Go to the documentation of this file.
1/*
2 * Replacements for snprintf() and vsnprintf()
3 *
4 * modified from Sten Gunterberg's BUGTRAQ post of 22 Jul 1997
5 * --nathan bryant <nathan@designtrust.com>
6 *
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.
12 *
13 * You don't have a /dev/null? Every Linux contains one for free!
14 *
15 * Because the format string is never even looked at, all current and
16 * possible future printf-conversions should be handled just fine.
17 *
18 * Written July 1997 by Sten Gunterberg (gunterberg@ergon.ch)
19 */
20
21#include <stdio.h>
22#include <stdlib.h>
23#include <stdarg.h>
24#include <string.h>
25
26static int
27needed (const char *fmt, va_list argp)
28{
29 static FILE *sink = NULL;
30
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 :-) */
34
35 if (sink == NULL)
36 {
37 if ((sink = fopen("/dev/null", "w")) == NULL)
38 {
39 perror("/dev/null");
40 exit(1);
41 }
42 }
43
44 return vfprintf(sink, fmt, argp);
45}
46
47int
48vsnprintf (char *buf, size_t max, const char *fmt, va_list argp)
49{
50 char *p;
51 int size;
52
53 if ((p = malloc(needed(fmt, argp) + 1)) == NULL)
54 {
55 fprintf(stderr, "vsnprintf: malloc failed, aborting\n");
56 abort();
57 }
58
59 if ((size = vsprintf(p, fmt, argp)) >= max)
60 size = -1;
61
62 strncpy(buf, p, max);
63 buf[max - 1] = 0;
64 free(p);
65 return size;
66}
67
68int
69snprintf (char *buf, size_t max, const char *fmt, ...)
70{
71 va_list argp;
72 int bytes;
73
74 va_start(argp, fmt);
75 bytes = vsnprintf(buf, max, fmt, argp);
76 va_end(argp);
77
78 return bytes;
79}
void * malloc(size_t)
void free(void *)
int snprintf(char *buf, size_t max, const char *fmt,...)
Definition: snprintf.c:69
static int needed(const char *fmt, va_list argp)
Definition: snprintf.c:27
int vsnprintf(char *buf, size_t max, const char *fmt, va_list argp)
Definition: snprintf.c:48