Back to index

nagios-plugins  1.4.16
vsnprintf.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 Yoann Vandoorselaere <yoann@prelude-ids.org>.
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 #ifdef HAVE_CONFIG_H
00020 # include <config.h>
00021 #endif
00022 
00023 /* Specification.  */
00024 #include <stdio.h>
00025 
00026 #include <errno.h>
00027 #include <limits.h>
00028 #include <stdarg.h>
00029 #include <stdlib.h>
00030 #include <string.h>
00031 
00032 #include "vasnprintf.h"
00033 
00034 /* Print formatted output to string STR.  Similar to vsprintf, but
00035    additional length SIZE limit how much is written into STR.  Returns
00036    string length of formatted string (which may be larger than SIZE).
00037    STR may be NULL, in which case nothing will be written.  On error,
00038    return a negative value.  */
00039 int
00040 vsnprintf (char *str, size_t size, const char *format, va_list args)
00041 {
00042   char *output;
00043   size_t len;
00044   size_t lenbuf = size;
00045 
00046   output = vasnprintf (str, &lenbuf, format, args);
00047   len = lenbuf;
00048 
00049   if (!output)
00050     return -1;
00051 
00052   if (output != str)
00053     {
00054       if (size)
00055         {
00056           size_t pruned_len = (len < size ? len : size - 1);
00057           memcpy (str, output, pruned_len);
00058           str[pruned_len] = '\0';
00059         }
00060 
00061       free (output);
00062     }
00063 
00064   if (len > INT_MAX)
00065     {
00066       errno = EOVERFLOW;
00067       return -1;
00068     }
00069 
00070   return len;
00071 }