vsprintf_s functionThe function vsprintf_s requires both the stdio.h and stdarg.h standard libraries and is used to write formatted output using a pointer to a list of arguments. The structure of the vsprintf_s function is as follows:
int vsprintf_s(char * buffer, size_t numberOfElements, const char * format, va_list argptr);
buffer is a pointer to the char array to which the function should write to.numberOfElements is the number of characters to be written.format is a pointer to a character array containing the format string.argptr is a list of arguments needed for the format string.vsprintf_s functionThe following code demonstrates the use of the vsprintf_s function:
#include<stdio.h>#include<stdarg.h>/*call_vsprintf_s is a wrapper function which converts "..." to "arglist" and then calls vsprintf_s function*/int call_vsprintf_s(char * buffer, size_t numberOfElements, char * format, ...) {int result;va_list arglist;va_start(arglist, format);result = vsprintf_s(buffer, numberOfElements, format, arglist);va_end(arglist);return result;}int main() {char buffer[100];int i = 10, j = 8;char format[] = "You scored %d/%d";int written = call_vsprintf_s(buffer, 15, format, j, i);printf("Characters Written: %d\n", written);printf("%s", buffer);return 0;}
Output:
Characters Written: 15
You scored 8/10
In the example above, the format string is copied to the buffer after the formatting is applied. The format string You scored %d/%d evaluates to You scored 8/10, because, in line 9, the argument right next to format is j and then i, which have the values 8 and 10 respectively. The function vsprintf_s also returns the number of characters written to the buffer in the variable written. At the end of the program, the number of characters written and the contents of the buffer are printed onto the standard output.
Note: The function above is not supported by the GCC compile, so you will get an
implicit declaration of function…error.
Use the following variant vsprintf to get the job done:
int vsprintf(char * buffer, const char * format, va_list argptr);
All parameters are the same as vsprintf_s, except that numberOfElements is not a parameter of vsprintf. The return value of the above function is the same as vsprintf_s.
Free Resources