In article , Michael B Allen <(E-Mail Removed)> writes:
> What is the rationale for snprintf to "return the number of characters
> (excluding the trailing '\0') which would have been written to the final
> string if enough space had been available"?
Others have already pointed out why this is the Right Thing. It's
also perhaps worth noting a real-world example of the Wrong Thing:
Microsoft's _snprintf, which returns -1 for both a too-short buffer
and a formatting error. *That* is obviously broken: the program
doesn't know whether enlarging the buffer will correct the problem,
or no amount of buffer space will fix it.
Consequently, any program that uses _snprintf and tries to implement
the reallocate-for-more-space pattern has to either impose some
arbitrary limit on how large the buffer will get, or try it until
allocation fails, if there's any possibility of a formatting error.
(Had Microsoft decided to return distinct error codes, their
_snprintf would be less efficient than a conforming snprintf, since
the program would have to heuristically determine the space needed,
but at least it would work.)