sprintf_sis a Microsoft implementation of the function sprintf where they patched a flaw, adding an argument to take a boundary value where the function is limited to write.
An equivalent was introduced in C++11: snprintf. But here, we are talking of C++03 syntax.
Signatures:
count_char_written sprintf(char* string_out, const char* output_template, VARIADIC_ARGS);
// and
count_char_written sprintf_s(char* string_out, size_t buffer_max_size, const char* output_template, VARIADIC_ARGS);
Functionnaly, sprintf_s is more advanced than sprintf, because it avoids overflows.
But sprintf_s is Microsoft only!
What to do if you want to port back a C++03 code written with sprintf_s to POSIX compatible syntax?
Today both
snprintfandvsnprintfshould be available everywhere with the exception of Windows with MSVC12 and older. The simplest way for you is to providesnprintf/vsnprintfon Windows where it is not available.Windows provides function
_vsnprintf_swhich is already similar tovsnprintf, but has following important differences with regards to what happens when provided buffer is too small:countargument which does not exist invsnprintf. To getvsnprintfbehavior you can pass_TRUNCATEhere.-1is returned instead of number of characters required. This can be fixed by using_vscprintffunction which only needs to be called if previous call to_vsnprintf_shas failed.Additionally those functions do not support format specifiers added in C99 such as
%zd. This cannot be easily resolved, you will have to avoid using them.Code below:
Note: Windows also provides
_vsnprintfwhich looks better suited for this implementation, but it does not terminate the resulting string. If you want to use it, you should be careful.