From 4ecaf22055282efee8a087248dea361f7246c109 Mon Sep 17 00:00:00 2001 From: "Andrey A. Chernov" Date: Wed, 24 Dec 1997 12:31:32 +0000 Subject: [PATCH] snprintf return value fixes to conform Single Unix specs: 1) if buffer size is smaller than arguments size, return buffer size, not arguments size as before. 2) if buffer size is 0, return 0, not EOF as before. (now it is compatible with Linux and Apache implementations too). NOTE: Single Unix specs says: If the value of n {buffer size} is zero on a call to snprintf(), an unspecified value less than 1 is returned. It means we can't return EOF since EOF can take *any* value in general not especially < 1. Better variant will be return -1 (it is less then 1 and different with n == 1 case) but -1 value is already occuped by EOF in our implementation, so we can't distinguish true IO error in that case. So 0 here is only possible case still conforming to Single Unix specs. --- lib/libc/stdio/snprintf.c | 11 ++++++++--- lib/libc/stdio/vsnprintf.c | 11 ++++++++--- 2 files changed, 16 insertions(+), 6 deletions(-) diff --git a/lib/libc/stdio/snprintf.c b/lib/libc/stdio/snprintf.c index 0e3c4566f55b..086f8b2b98ce 100644 --- a/lib/libc/stdio/snprintf.c +++ b/lib/libc/stdio/snprintf.c @@ -39,7 +39,7 @@ static char sccsid[] = "@(#)snprintf.c 8.1 (Berkeley) 6/4/93"; #endif static const char rcsid[] = - "$Id$"; + "$Id: snprintf.c,v 1.5 1997/02/22 15:02:29 peter Exp $"; #endif /* LIBC_SCCS and not lint */ #include @@ -65,8 +65,11 @@ snprintf(str, n, fmt, va_alist) va_list ap; FILE f; + if (n == 0) + return (0); if ((int)n < 1) return (EOF); + n--; #if __STDC__ va_start(ap, fmt); #else @@ -75,9 +78,11 @@ snprintf(str, n, fmt, va_alist) f._file = -1; f._flags = __SWR | __SSTR; f._bf._base = f._p = (unsigned char *)str; - f._bf._size = f._w = n - 1; + f._bf._size = f._w = n; ret = vfprintf(&f, fmt, ap); *f._p = 0; va_end(ap); - return (ret); + if (ret == EOF) + return (ret); + return (ret > (int)n ? n : ret); } diff --git a/lib/libc/stdio/vsnprintf.c b/lib/libc/stdio/vsnprintf.c index 8837c2e05144..ec13305ba69c 100644 --- a/lib/libc/stdio/vsnprintf.c +++ b/lib/libc/stdio/vsnprintf.c @@ -39,7 +39,7 @@ static char sccsid[] = "@(#)vsnprintf.c 8.1 (Berkeley) 6/4/93"; #endif static const char rcsid[] = - "$Id$"; + "$Id: vsnprintf.c,v 1.5 1997/02/22 15:02:45 peter Exp $"; #endif /* LIBC_SCCS and not lint */ #include @@ -54,13 +54,18 @@ vsnprintf(str, n, fmt, ap) int ret; FILE f; + if (n == 0) + return (0); if ((int)n < 1) return (EOF); + n--; f._file = -1; f._flags = __SWR | __SSTR; f._bf._base = f._p = (unsigned char *)str; - f._bf._size = f._w = n - 1; + f._bf._size = f._w = n; ret = vfprintf(&f, fmt, ap); *f._p = 0; - return (ret); + if (ret == EOF) + return (ret); + return (ret > (int)n ? n : ret); }