I’m porting an existing Windows application to Linux.
The most of the OS APIs\ Microsoft non-standard extension functions can be easily (more or less…) replaced by equivalent Linux\ GCC APIs, however, I don’t know how to deal with sprintf_s which gets variable numbers of arguments.
Does anyone have an idea (If you can please put the code example as well) for that?
Thank you all in advance.
First, can you just port your code to use C++ iostreams instead (for example
ostringstream)? This would completely remove all the possible issues with thesprintfline of functions, and if there are a limited number of call points is probably the best option.If that isn’t an option: The
sprintf_sfunction is basically a helper to prevent mistakes (and external abuse to cause buffer overflows. From http://msdn.microsoft.com/en-us/library/ce3zzk1k%28VS.80%29.aspx we learn that it does two things: It checks the format string for valid formats (this doesn’t mean it does type checking – it still can’t do that), and it allows a max length to be specified.The best replacement will be
snprintfwhich does have limitations compared tosprintf_s. It won’t do format string validation. And not all versions guarantee that the final string will be null terminated: You always want to also store a null into the last character of your buffer after the call to ensure that the final string is null terminated.