Recovering graceflly from a failed vsnprintf on msvc2008
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 leng开发者_如何转开发th 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?
The function you're looking for is _vscprintf (or _vscwprintf). These return the number of characters required without actually formatting anything.
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
.)
精彩评论