What is the snprintf() function in C?

The snprintf() function redirects the output of the standard printf() function to a buffer.

In C it is defined as:

svg viewer

It is important to note that snprintf() appends a null character to the end of the resulting output. This null character is also counted towards the size of the string.

The function returns an integer, which is the number of characters that would have been written if the buff_size argument had been large enough. Therefore, the buffer is only considered to be completely written if the returned value is non-negative and less than buff_size.

This method is useful for avoiding the repetition of a formatted string. One can build a string once using printf("%s", myBuffer) instead of usingprint("%d,%s,%f,%d", a,b,c,d), which is unnecessarily complex and cumbersome​.

The following code snippet demonstrates how to use ​the snprintf() function:

#include<stdio.h>
int main() {
char buffer[100];
int returnValue, buff_size = 38;
char name[] = "Tony";
int age = 21;
returnValue = snprintf(buffer, buff_size, "My name is %s and I am %d years old", name, age);
if (returnValue > 0 && returnValue < buff_size)
{
printf("%s\n", buffer);
printf("Return value: %d", returnValue);
}
else
{
printf("Buffer was not written completely. Note the output below:\n");
printf("%s\n", buffer);
printf("Return value: %d", returnValue);
}
}
Copyright ©2024 Educative, Inc. All rights reserved