VOOZH about

URL: https://www.geeksforgeeks.org/c/snprintf-c-library/

⇱ snprintf() in C - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

snprintf() in C

Last Updated : 7 Mar, 2025

In C, snprintf() function is a standard library function that is used to print the specified string till a specified length in the specified format. It is defined in the <stdio.h> header file.

In this article, we will learn about snprintf() function in C and how to use it in our program.

Syntax

Parameters

  • str: It is a pointer to the buffer.
  • size: It 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.

Return Value

  • The number of characters that would have been written on the buffer, if 'n' had been sufficiently large.
  • If an encoding error occurs, a negative number is returned.

Examples of snprintf()

Example 1:

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


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

Example 2:


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.

Characteristics of snprintf() Method

  • The snprintf() function formats and stores a series of characters and values in the array buffer. 
  • The snprintf() function accepts an argument 'n', which indicates the maximum number of characters (including at the end of null character) to be written to buffer. 
  • The snprintf() function is used to redirect the output of  printf() function onto a buffer. 
  • The snprintf() also returns the number characters that were supposed to be written onto the buffer (excluding the null terminator), irrespective of the value of 'n' passed.
  • So, only when the returned value is non-negative and less than 'n', the string has been completely written as expected.
Comment
Article Tags: