views:

85

answers:

2

I'm looking for a way to use some variant of vsnprintf() with a buffer that can possibly be longer than the input buffer without triggering an error to the user.

So far I've found that vsnprintf() and its variants silently truncate the string when the buffer is too small but they don't return the actual length of the string so I can't try it again with a longer buffer. They return -1.

On the other hand, the vsnprintf_s() variants, when faced with this error, call

_VALIDATE_RETURN(("Buffer too small", 0), ERANGE, -1);

Which in turn eventually calls _CrtDbgReportW(), possibly only in debug. They do this even before calling the user supplied "invalid parameter handler"

All I want is to be able to recover with no user interaction by getting the actual size I need to allocate and calling the function again. is that possible?

A: 

if you supply the length of the output buffer in n, you then know that no more than n characters was written.

vsnprintf returns the number of characters that would have been written if the buffer was long enough.

So, the return value is the size of the buffer you need.

If you set n=0, nothing will be written, but vsnprintf will tell you how big the buffer needs to be.

(I just re-read the vsnprintf doc, you need to add 1 byte to the return value for the NUL.)

philcolbourn
in VC, vsnprintf returns -1 if it can't fit the data into the buffer.
shoosh
try _scprintf then. I should add the you are right, the VC implementation is different.
philcolbourn
A link to the MS doc with the perfect example!http://msdn.microsoft.com/en-us/library/t32cf9tb(VS.80).aspx
philcolbourn
+2  A: 

The function you're looking for is _vscprintf (or _vscwprintf). These return the number of characters required without actually formatting anything.

Peter Ruderman