Open In App

snprintf() in C library

The snprintf() function is defined in the <stdio.h> header file and is used to store the specified string till a specified length in the specified format.

Characteristics of snprintf() method:



Syntax: The syntax of snprintf() method is: 

int snprintf(char *str, size_t size, const char *format, …);



Parameters:

Return value:

Below is an example to illustrate the working of snprintf() method:

Example 1:




// C program to demonstrate snprintf()
#include <stdio.h>
 
int main()
{
    char buffer[50];
    char* s = "geeksforgeeks";
 
    // Counting the character and storing
    // in buffer using snprintf
    printf("Writing %s onto buffer"
           " with capacity 6",
           s);
    int j = snprintf(buffer, 6, "%s\n", s);
 
    // Print the string stored in buffer and
    // character count
    printf("\nString written on "
           "buffer = %s", buffer);
    printf("\nValue returned by "
           "snprintf() method = %d\n", j);
 
    return 0;
}

Output
Writing geeksforgeeks onto buffer with capacity 6
String written on buffer = geeks
Value returned by snprintf() method = 14

Example 2:




// C program to demonstrate snprintf()
#include <stdio.h>
 
int main()
{
    char buffer[50];
   
    // join two or more strings
    char* str1 = "quick";
    char* str2 = "brown";
    char* str3 = "lazy";
    int max_len = sizeof buffer;
 
    int j = snprintf(buffer, max_len,
                 "The %s %s fox jumped over the %s dog.",
                 str1, str2, str3);
    printf("\nThe number of bytes printed to 'buffer' "
           "(excluding the null terminator) is %d\n",
           j);
    if (j >= max_len)
        fputs("Buffer length exceeded; string truncated",
              stderr);
    puts("Joined string:");
    puts(buffer);
 
    return 0;
}

Output
The number of bytes printed to 'buffer' (excluding the null terminator) is 45
Joined string:
The quick brown fox jumped over the lazy dog.

Article Tags :