Home » C programs » stdio.h header file functions

snprintf() function in C language with Example

Here, we are going to learn about the snprintf() function of library function stdio.h in C language with its syntax, example.
Submitted by Raja Sethupathi V, on February 06, 2019

snprintf() function in C

The snprintf() function is defined in the <stdio.h> header file.

Prototype:

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

Parameters:

  • str - is a Buffer.
  • size - is a maximum number of bytes.
  • format - c string that contains a format that follows the same specifications as format in printf.
  • ... - the optional (...) arguments are just the string formats like “%d” as seen in printf.

Return type: int

Use of function:

  • The snprintf() formats and stores a series of characters and values in the array buffer.
  • It redirects the output of printf to the buffer.
  • Using snprintf() build a string once and use %s instead of %d, %s, %f, %ld every time.

snprintf() example in C

#include <stdio.h> 

int main() { 
	char* r = "Includehelp.com"; 
	char buf[100]; 
	
	// in buffer using snprintf 
	int i = snprintf(buf, 12, "%s\n", r); 
	
	// Print the string stored in buffer and 
	// character count 
	printf("string is:\n%s\ncharacter count = %d\n", buf, i); 
	
	return 0; 
} 

Output

string is:
Includehelp
character count = 16




Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.



Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing » Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.