Back to index

nagios-plugins  1.4.16
snprintf.c
Go to the documentation of this file.
00001 /* Formatted output to strings.
00002    Copyright (C) 2004, 2006-2010 Free Software Foundation, Inc.
00003    Written by Simon Josefsson and Paul Eggert.
00004 
00005    This program is free software; you can redistribute it and/or modify
00006    it under the terms of the GNU General Public License as published by
00007    the Free Software Foundation; either version 3, or (at your option)
00008    any later version.
00009 
00010    This program is distributed in the hope that it will be useful,
00011    but WITHOUT ANY WARRANTY; without even the implied warranty of
00012    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
00013    GNU General Public License for more details.
00014 
00015    You should have received a copy of the GNU General Public License along
00016    with this program; if not, write to the Free Software Foundation,
00017    Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.  */
00018 
00019 #include <config.h>
00020 
00021 /* Specification.  */
00022 #include <stdio.h>
00023 
00024 #include <errno.h>
00025 #include <limits.h>
00026 #include <stdarg.h>
00027 #include <stdlib.h>
00028 #include <string.h>
00029 
00030 #include "vasnprintf.h"
00031 
00032 /* Print formatted output to string STR.  Similar to sprintf, but
00033    additional length SIZE limit how much is written into STR.  Returns
00034    string length of formatted string (which may be larger than SIZE).
00035    STR may be NULL, in which case nothing will be written.  On error,
00036    return a negative value.  */
00037 int
00038 snprintf (char *str, size_t size, const char *format, ...)
00039 {
00040   char *output;
00041   size_t len;
00042   size_t lenbuf = size;
00043   va_list args;
00044 
00045   va_start (args, format);
00046   output = vasnprintf (str, &lenbuf, format, args);
00047   len = lenbuf;
00048   va_end (args);
00049 
00050   if (!output)
00051     return -1;
00052 
00053   if (output != str)
00054     {
00055       if (size)
00056         {
00057           size_t pruned_len = (len < size ? len : size - 1);
00058           memcpy (str, output, pruned_len);
00059           str[pruned_len] = '\0';
00060         }
00061 
00062       free (output);
00063     }
00064 
00065   if (INT_MAX < len)
00066     {
00067       errno = EOVERFLOW;
00068       return -1;
00069     }
00070 
00071   return len;
00072 }