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

C stdio.h Library Functions Programs »





Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.