diff options
author | Paul Eggert <eggert@cs.ucla.edu> | 2006-08-10 19:09:33 +0000 |
---|---|---|
committer | Paul Eggert <eggert@cs.ucla.edu> | 2006-08-10 19:09:33 +0000 |
commit | ffafcd29981674cdd1904fcc5a8b015fb5787e5f (patch) | |
tree | eef690e32d63309783d214fb2c79169c72d63859 /lib/snprintf.c | |
parent | 01dddfef2ae8caf7818dd94ca5c4e1d6f3b9140a (diff) | |
download | coreutils-ffafcd29981674cdd1904fcc5a8b015fb5787e5f.tar.xz |
Import from gnulib, to support new getaddrinfo implementation of gnulib.
Diffstat (limited to 'lib/snprintf.c')
-rw-r--r-- | lib/snprintf.c | 76 |
1 files changed, 76 insertions, 0 deletions
diff --git a/lib/snprintf.c b/lib/snprintf.c new file mode 100644 index 000000000..c281f7c58 --- /dev/null +++ b/lib/snprintf.c @@ -0,0 +1,76 @@ +/* Formatted output to strings. + Copyright (C) 2004, 2006 Free Software Foundation, Inc. + Written by Simon Josefsson and Paul Eggert. + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2, or (at your option) + any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License along + with this program; if not, write to the Free Software Foundation, + Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ + +#ifdef HAVE_CONFIG_H +# include <config.h> +#endif + +#include "snprintf.h" + +#include <errno.h> +#include <limits.h> +#include <stdarg.h> +#include <stdlib.h> +#include <string.h> + +#include "vasnprintf.h" + +/* Some systems, like OSF/1 4.0 and Woe32, don't have EOVERFLOW. */ +#ifndef EOVERFLOW +# define EOVERFLOW E2BIG +#endif + +/* Print formatted output to string STR. Similar to sprintf, but + additional length SIZE limit how much is written into STR. Returns + string length of formatted string (which may be larger than SIZE). + STR may be NULL, in which case nothing will be written. On error, + return a negative value. */ +int +snprintf (char *str, size_t size, const char *format, ...) +{ + char *output; + size_t len; + va_list args; + + va_start (args, format); + len = size; + output = vasnprintf (str, &len, format, args); + va_end (args); + + if (!output) + return -1; + + if (output != str) + { + if (size) + { + memcpy (str, output, size - 1); + str[size - 1] = '\0'; + } + + free (output); + } + + if (INT_MAX < len) + { + errno = EOVERFLOW; + return -1; + } + + return len; +} |