]> git.cworth.org Git - tar/blob - gnu/snprintf.c
upstream: Fix extraction of device nodes.
[tar] / gnu / snprintf.c
1 /* -*- buffer-read-only: t -*- vi: set ro: */
2 /* DO NOT EDIT! GENERATED AUTOMATICALLY! */
3 /* Formatted output to strings.
4    Copyright (C) 2004, 2006-2010 Free Software Foundation, Inc.
5    Written by Simon Josefsson and Paul Eggert.
6
7    This program is free software; you can redistribute it and/or modify
8    it under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 3, or (at your option)
10    any later version.
11
12    This program is distributed in the hope that it will be useful,
13    but WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15    GNU General Public License for more details.
16
17    You should have received a copy of the GNU General Public License along
18    with this program; if not, write to the Free Software Foundation,
19    Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.  */
20
21 #include <config.h>
22
23 /* Specification.  */
24 #include <stdio.h>
25
26 #include <errno.h>
27 #include <limits.h>
28 #include <stdarg.h>
29 #include <stdlib.h>
30 #include <string.h>
31
32 #include "vasnprintf.h"
33
34 /* Print formatted output to string STR.  Similar to sprintf, 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.  */
39 int
40 snprintf (char *str, size_t size, const char *format, ...)
41 {
42   char *output;
43   size_t len;
44   size_t lenbuf = size;
45   va_list args;
46
47   va_start (args, format);
48   output = vasnprintf (str, &lenbuf, format, args);
49   len = lenbuf;
50   va_end (args);
51
52   if (!output)
53     return -1;
54
55   if (output != str)
56     {
57       if (size)
58         {
59           size_t pruned_len = (len < size ? len : size - 1);
60           memcpy (str, output, pruned_len);
61           str[pruned_len] = '\0';
62         }
63
64       free (output);
65     }
66
67   if (INT_MAX < len)
68     {
69       errno = EOVERFLOW;
70       return -1;
71     }
72
73   return len;
74 }