Subject: Re: Query about return value of snprintf
To: None <mcr@solidum.com>
From: Chris G. Demetriou <cgd@netbsd.org>
List: tech-userlevel
Date: 06/17/1999 14:45:28
mcr@solidum.com writes:
>   The NetBSD man page says that we do:
> 
>      These functions return the number of characters printed (not including
>      the trailing `\0' used to end output to strings).
> 
>   Which is what I expected.

No, that's part of what it says.

Further it says:

     snprintf() and vsnprintf() will write at most size-1 of the characters
     printed into the output string (the size'th character then gets the ter-
     minating `\0'); if the return value is greater than or equal to the size
     argument, the string was too short and some of the printed characters
     were discarded.

i.e. it actually returns the number of characters that would have been
printed, given an adequately-sided buffer.


> RETURN VALUE
>        If  the output was truncated, the return value is -1, oth-
>        erwise it is the number of characters stored, not  includ-
>        ing the terminating null.

I consider the BSD behaviour much preferred to what you quote as the
GNU libc behaviour.

If the caller wants to know that the output was truncated, they can do
a simple comparison in either case.  However with the BSD return
value, they can then go an allocate a right-sized buffer if their
application needs it, and reformat the complete string.  From what
you've quoted, it doesn't sound like there's any good way to figure
out the 'right size' of a right-sized buffer with the glibc implementation.


>   I realize that this isn't POSIX, but are there any opinions as what is
> reasonable? I see reasons why the GNU version is useful, but I also see that
> it may break existing code.

Actually, see above; i'd say that GNU version is strictly less useful
than the BSD version, as it returns less information.



cgd
-- 
Chris Demetriou - cgd@netbsd.org - http://www.netbsd.org/People/Pages/cgd.html
Disclaimer: Not speaking for NetBSD, just expressing my own opinion.