Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

snprintf() in C library

  • Difficulty Level : Basic
  • Last Updated : 18 Jul, 2021

The snprintf() function formats and stores a series of characters and values in the array buffer. The snprintf() function with the addition of the n argument, which indicates the maximum number of characters (including at the end of null character) to be written to buffer. It is defined in <stdio.h> header file.

The snprintf() function is used to redirect the  output of  printf() function onto a buffer. 

Take a step-up from those "Hello World" programs. Learn to implement data structures like Heap, Stacks, Linked List and many more! Check out our Data Structures in C course to start learning today.

The snprintf() also returns the number characters written onto the buffer, similar to the printf statement, which returns the number of characters that is printed in stdout.

Syntax : 
 



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

*str : is a buffer.
size : is the maximum number of bytes
(characters) that will be written to the buffer.
format : C string that contains a format
string that follows the same specifications as format in printf
... : the optional ( ā€¦) arguments 
are just the string formats like (ā€œ%dā€, myint) as seen in printf.

 

C




// 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
    int j = snprintf(buffer, 6, "%s\n", s);
 
    // Print the string stored in buffer and
    // character count
    printf("string:\n%s\ncharacter count = %d\n",
                                     buffer, j);
 
    return 0;
}

Output: 
 

string:
geeks
character count = 14

 

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!