snprintf function --output format string to string variable (with maximum character limit)
The snprintf function has the same functionality as the sprintf function, but you can specify the maximum number of characters. It can be used when you want to ensure that a buffer overrun is prevented. The snprintf function can be used by loading stdio.h.
#include <stdio.h> int snprintf (char * restrict s, size_t n, const char * restrict format, ...);
sprintf function. If the number of characters exceeds "n -1", the character string after that is not written, and the null character "\ 0" is written.
Snprintf function sample
This is a sample of the snprintf function.
#include <stdio.h> #include <stdint.h> int main (void) { const char * name = "long_long_long_name"; int32_t age = 40; char message [16]; // Since the maximum number of characters is limited, buffer overrun does not occur. snprintf (message, 16, "I'm%s. Age is%d.", name, age); printf("%s\n", message); }
This is the output result. The output is missing.
I'm long_long_l
There is no buffer overrun, but programmatically, this is probably not the correct result, so it is likely that you will need to modify your program, such as increasing the length of the buffer.