mountlist: Use Linux code on Android.
[gnulib.git] / lib / c-vsnprintf.c
blob1bfab608323cf0945501ad38860a3ff7c71b85b1
1 /* Formatted output to strings in C locale.
2 Copyright (C) 2004, 2006-2019 Free Software Foundation, Inc.
3 Written by Simon Josefsson and Yoann Vandoorselaere <yoann@prelude-ids.org>.
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 2, 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 #ifdef HAVE_CONFIG_H
20 # include <config.h>
21 #endif
23 /* Specification. */
24 #include <stdio.h>
26 #include <errno.h>
27 #include <limits.h>
28 #include <stdarg.h>
29 #include <stdlib.h>
30 #include <string.h>
32 #include "c-vasnprintf.h"
34 /* Print formatted output to string STR. Similar to vsprintf, but
35 additional length SIZE limit how much is written into STR. Returns
36 string length of formatted string (which may be larger than SIZE).
37 STR may be NULL, in which case nothing will be written. On error,
38 return a negative value.
40 Formatting takes place in the C locale, that is, the decimal point
41 used in floating-point formatting directives is always '.'. */
42 int
43 c_vsnprintf (char *str, size_t size, const char *format, va_list args)
45 char *output;
46 size_t len;
47 size_t lenbuf = size;
49 output = c_vasnprintf (str, &lenbuf, format, args);
50 len = lenbuf;
52 if (!output)
53 return -1;
55 if (output != str)
57 if (size)
59 size_t pruned_len = (len < size ? len : size - 1);
60 memcpy (str, output, pruned_len);
61 str[pruned_len] = '\0';
64 free (output);
67 if (len > INT_MAX)
69 errno = EOVERFLOW;
70 return -1;
73 return len;