timevar: import from Bison.
[gnulib.git] / lib / c-snprintf.c
blob454339f918d1cba64a1d03700104206f513fa17e
1 /* Formatted output to strings in C locale.
2 Copyright (C) 2004, 2006-2018 Free Software Foundation, Inc.
3 Written by Simon Josefsson and Paul Eggert.
4 Modified for C locale by Ben Pfaff.
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.
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.
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/>. */
19 #include <config.h>
21 /* Specification. */
22 #include <stdio.h>
24 #include <errno.h>
25 #include <limits.h>
26 #include <stdarg.h>
27 #include <stdlib.h>
28 #include <string.h>
30 #include "c-vasnprintf.h"
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.
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, ...)
43 char *output;
44 size_t len;
45 size_t lenbuf = size;
46 va_list args;
48 va_start (args, format);
49 output = c_vasnprintf (str, &lenbuf, format, args);
50 len = lenbuf;
51 va_end (args);
53 if (!output)
54 return -1;
56 if (output != str)
58 if (size)
60 size_t pruned_len = (len < size ? len : size - 1);
61 memcpy (str, output, pruned_len);
62 str[pruned_len] = '\0';
65 free (output);
68 if (INT_MAX < len)
70 errno = EOVERFLOW;
71 return -1;
74 return len;