Back to index

citadel  8.12
snprintf.c
Go to the documentation of this file.
00001 /*
00002  * Replacements for snprintf() and vsnprintf()
00003  *
00004  * modified from Sten Gunterberg's BUGTRAQ post of 22 Jul 1997
00005  * --nathan bryant <nathan@designtrust.com>
00006  *
00007  * Use it only if you have the "spare" cycles needed to effectively
00008  * do every snprintf operation twice! Why is that? Because everything
00009  * is first vfprintf()'d to /dev/null to determine the number of bytes.
00010  * Perhaps a bit slow for demanding applications on slow machines,
00011  * no problem for a fast machine with some spare cycles.
00012  *
00013  * You don't have a /dev/null? Every Linux contains one for free!
00014  *
00015  * Because the format string is never even looked at, all current and
00016  * possible future printf-conversions should be handled just fine.
00017  *
00018  * Written July 1997 by Sten Gunterberg (gunterberg@ergon.ch)
00019  */
00020 
00021 #include <stdio.h>
00022 #include <stdlib.h>
00023 #include <stdarg.h>
00024 #include <string.h>
00025 
00026 static int
00027 needed (const char *fmt, va_list argp)
00028 {
00029   static FILE *sink = NULL;
00030 
00031   /* ok, there's a small race here that could result in the sink being
00032    * opened more than once if we're threaded, but I'd rather ignore it than
00033    * spend cycles synchronizing :-) */
00034 
00035   if (sink == NULL)
00036     {
00037       if ((sink = fopen("/dev/null", "w")) == NULL)
00038        {
00039          perror("/dev/null");
00040          exit(1);
00041        }
00042     }
00043 
00044   return vfprintf(sink, fmt, argp);
00045 }
00046 
00047 int
00048 vsnprintf (char *buf, size_t max, const char *fmt, va_list argp)
00049 {
00050   char *p;
00051   int size;
00052 
00053   if ((p = malloc(needed(fmt, argp) + 1)) == NULL)
00054     {
00055       fprintf(stderr, "vsnprintf: malloc failed, aborting\n");
00056       abort();
00057     }
00058 
00059   if ((size = vsprintf(p, fmt, argp)) >= max)
00060     size = -1;
00061 
00062   strncpy(buf, p, max);
00063   buf[max - 1] = 0;
00064   free(p);
00065   return size;
00066 }
00067 
00068 int
00069 snprintf (char *buf, size_t max, const char *fmt, ...)
00070 {
00071   va_list argp;
00072   int bytes;
00073 
00074   va_start(argp, fmt);
00075   bytes = vsnprintf(buf, max, fmt, argp);
00076   va_end(argp);
00077 
00078   return bytes;
00079 }