What is sprintf_s in C?

The sprintf_s is defined in the stdio.h header file and is the security-enhanced alternate of the sprintf function. It uses a format string and corresponding arguments to generate a string that stores in the provided destination string. What makes sprintf_s different from the normal sprintf is that it performs extra run-time checks on the arguments before they are executed.

Syntax

Following is the declaration syntax for the sprintf_s function:

Parameters

The sprintf_s function takes in 4 arguments:

  • ws: The pointer to the destination string where the formatted string will be stored

  • format: The pointer to the format string, which may include format specifiers like %s.

  • ...: The list of arguments corresponding to the specifiers used (if any) in the format string. This can have zero to as many arguments as the number of specifiers used in the format string.

Return value

sprintf_s can have two potential returns values:

  • A negative number if there is an error in execution or the length of the formatted string is greater than the given length.

  • The number of characters in the formatted string in case of successful execution of the function.

Example

Following is an example of how we can use the sprintf_s function to generate and copy a formatted string to a pointed string:

All bounds-checked functions (with “_s” suffix in their names) including the sprintf_s function are only guaranteed to work if __STDC_LIB_EXT1__ is pre-defined by the implementation and if the user defines __STDC_WANT_LIB_EXT1__ to int 1 before including stdio.h header file.

//__STDC_WANT_LIB_EXT1__ has to be defined to int 1 for sprintfs to work
#define __STDC_WANT_LIB_EXT1__ 1;
#include <stdio.h>
int main ()
{
// destination string array
char dest_str [50];
// string array to use as argument
char var [10] = "a ton";
// int variable to store the return value of sprintf_s
int ch_count;
// only use sprintf_s if __STDC_LIB_EXT1__ is already defined
#ifdef __STDC_LIB_EXT1__
ch_count = sprintf_s ( dest_str, "Educative has %s courses", var );
#endif
// use sprintf function
ch_count = sprintf ( dest_str, "Educative has %s courses", var );
// printing out the destination string
printf(dest_str);
return 0;
}

In this example, we declared two strings and initialized the one we intend to use as the argument corresponding to the specifier used in the format string. We now check if __STDC_LIB_EXT1__ is defined and then use the sprintf_s function and pass it a format string along with the argument we created.sprint_s then generated the formatted output and stored it in the destination string. Finally, we printed out the complete string using the printf.

Free Resources

Copyright ©2024 Educative, Inc. All rights reserved