"Fossies" - the Fresh Open Source Software Archive

Member "citadel/snprintf.c" (5 Jun 2021, 1853 Bytes) of package /linux/www/citadel.tar.gz:


As a special service "Fossies" has tried to format the requested source page into HTML format using (guessed) C and C++ source code syntax highlighting (style: standard) with prefixed line numbers and code folding option. Alternatively you can here view or download the uninterpreted source code file. For more information about "snprintf.c" see the Fossies "Dox" file reference documentation.

    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 
   26 static int
   27 needed (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 
   47 int
   48 vsnprintf (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 
   68 int
   69 snprintf (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 }