root/maint/gnulib/lib/c-snprintf.c

/* [previous][next][first][last][top][bottom][index][help] */

DEFINITIONS

This source file includes following definitions.
  1. c_snprintf

   1 /* Formatted output to strings in C locale.
   2    Copyright (C) 2004, 2006-2021 Free Software Foundation, Inc.
   3    Written by Simon Josefsson and Paul Eggert.
   4    Modified for C locale by Ben Pfaff.
   5 
   6    This program is free software; you can redistribute it and/or modify
   7    it under the terms of the GNU General Public License as published by
   8    the Free Software Foundation; either version 3, or (at your option)
   9    any later version.
  10 
  11    This program is distributed in the hope that it will be useful,
  12    but WITHOUT ANY WARRANTY; without even the implied warranty of
  13    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  14    GNU General Public License for more details.
  15 
  16    You should have received a copy of the GNU General Public License along
  17    with this program; if not, see <https://www.gnu.org/licenses/>.  */
  18 
  19 #include <config.h>
  20 
  21 /* Specification.  */
  22 #include <stdio.h>
  23 
  24 #include <errno.h>
  25 #include <limits.h>
  26 #include <stdarg.h>
  27 #include <stdlib.h>
  28 #include <string.h>
  29 
  30 #include "c-vasnprintf.h"
  31 
  32 /* Print formatted output to string STR.  Similar to sprintf, but
  33    additional length SIZE limit how much is written into STR.  Returns
  34    string length of formatted string (which may be larger than SIZE).
  35    STR may be NULL, in which case nothing will be written.  On error,
  36    return a negative value.
  37 
  38    Formatting takes place in the C locale, that is, the decimal point
  39    used in floating-point formatting directives is always '.'. */
  40 int
  41 c_snprintf (char *str, size_t size, const char *format, ...)
     /* [previous][next][first][last][top][bottom][index][help] */
  42 {
  43   char *output;
  44   size_t len;
  45   size_t lenbuf = size;
  46   va_list args;
  47 
  48   va_start (args, format);
  49   output = c_vasnprintf (str, &lenbuf, format, args);
  50   len = lenbuf;
  51   va_end (args);
  52 
  53   if (!output)
  54     return -1;
  55 
  56   if (output != str)
  57     {
  58       if (size)
  59         {
  60           size_t pruned_len = (len < size ? len : size - 1);
  61           memcpy (str, output, pruned_len);
  62           str[pruned_len] = '\0';
  63         }
  64 
  65       free (output);
  66     }
  67 
  68   if (INT_MAX < len)
  69     {
  70       errno = EOVERFLOW;
  71       return -1;
  72     }
  73 
  74   return len;
  75 }

/* [previous][next][first][last][top][bottom][index][help] */