C Programming

snprintf Function in C

In the snprintf() function, we want to learn how to format the data. The data formatting is essential when we are writing some status of the process or any module to a file, and another module can access that. For that purpose, we want to share this data between modules. In this case, we want to format our data so that other modules can understand it in the same way.

snprintf() Function Prototype

The snprintf() function is a predefined data type. Its definition is written in a standard header file in C named <stdio.h> header file.

Characteristics of snprintf() Function

int snprintf ( char *st , max_size ,const char *format , ….);

Here, we use several parameters, such as the function of these parameters:

  • *st is a buffer that can contain the string.
  • max_size: Highest number of characters that a buffer can contain.
  • Format that contains a string and other specifications like printf() function.
  • snprintf() function returns an integer value, and its job is to count the number of characters inside the buffer.

Programming Example 1

Here, we will see the implementation of snprintf() function:

#include<stdio.h>

#include<string.h>

int main ( )
{
    char buff_max [ 15 ] ;  // declaring a string
    int x = 15 ;
    double y = 26.5 ;
snprintf( buff_max , 14 , "Examine the overflow test , the values of x = %d and y = %lf " , x , y ) ; // uses of snprintf() function
printf( " %s \n ", buff_max ) ;     //print the value of the string
    return 0 ;
}

Output

Explanation

In this programming example, we will use the snprintf() function to format a string. Here, we declare a string named “buff_max”, which holds a maximum of 15 characters, except we declare an integer type variable x and double type variable y.

Now, if we use the snprintf() function, we must pass some arguments inside its parenthesis. The arguments are the first of all the strings. We have to mention the size that the buffer can accumulate; the third parameter is the formatted string, and then the variable.

The advantage of using the snprintf() function is that only 14 characters can be printed, and the rest of the characters are ignored. The program will be safe, and the program is not crashing.

Programming Example 2

In this programming example, we will see another example of snprintf() function:

#include<stdio.h>

#include<string.h>

#define MAX_BUFF 1024

#define SIZE_NAME (15)

typedef struct
{
    char name [ SIZE_NAME ] ;       // declaring a string
    unsigned int rollno ;
    double marks ;
}STUDENT ;                   // creating user-defined data type
int main( intargc , char *argv[] )
{
    char buffer[MAX_BUFF] = {0} ;
    STUDENT s1 = { .name = " Avishek " , .rollno = 6 , .marks = 77.17 } ;
snprintf( buffer , sizeof ( buffer) , " %s %d %lf " , s1.name , s1.rollno , s1.marks ) ;        // uses of snprintf() function
printf( " Buffer = %s \n " , buffer ) ;
    return 0 ;
}

Output

Explanation

In this programming example, we will define the Structure name STUDENT. The data members of the STUDENT are name, roll no, and marks. Inside the main() function. we declare a variable s1 which is STUDENT datatype. If we want to print the value of each determent of the s1 variable, we will use the snprintf() function. The parameters of the snprintf are buffer, size of the buffer, the format of the string, and all the data members that need to be formatted. If we print the buffer, the output will be shown to the monitor as formatted output.

Programming Example 3

Let us take another important example of the snprintf() function and how it works.

#include<stdio.h>

#include<stdlib.h>

#include<string.h>

#define SIZE_BUFFER 1024

#define SIZE_NAME (20)

#define FORMAT_STRING "(%s,%d,%0.2lf),"

#define SIZE_BUFFER 1024
#define SIZE_NAME (20)
#define FORMAT_STRING "(%s,%d,%0.2lf),"
typedef struct
{
    char name[SIZE_NAME] ;
    unsigned int rollno ;
    double percentage ;
}PERSON ;       // defining a structure.
int main( intargc , char *argv[] )
{
       char buffer[SIZE_BUFFER] = {0} ;     // declaring a buffer.
       PERSON student_data[] = {{.name="Raul", .rollno=1020, .percentage=72.30334},\
                               {.name="Paul", .rollno=1021, .percentage=86.3456}\
} ; // creating an array of structure.
       int num_students = sizeof(student_data)/sizeof(PERSON);
       int pos = 0 ;
for(int i=0; i<num_students;i++)
       {
       pos += snprintf(buffer+pos,sizeof(buffer),FORMAT_STRING,student_data[i].name,student_data[i].rollno,
       student_data[i].percentage) ;
       }
printf( " buffer = [ %s ] \n " , buffer ) ;
       return 0 ;
}

Output

Explanation

Here, we take an array of structures and see the snprintf() function process. We define a structure named PERSON, and inside the main() function, we will declare an array of the structures of the PERSON data type and assign some value to this array. We can use a loop for the counter. At last, we will print the whole buffer with all the data. We are continuously iterating over this array of structures. Now, we save all the data into this buffer, depending on the position.

For the first time, the first student came, and it will write some data on this buffer. Then, the position’s value will change, and the buffer will write for that position. That’s how it works.

Advantage of Using snprintf() Function

The advantage of using the snprintf() function is that suppose the buffer is overflowing by the character from its maximum size. The program will be secure to avoid a crash. The rest of the characters are ignored by the snprintf() function, which will run the program.

Conclusion

In the C language, similar to the printf() function, another function named snprintf() is used to format the string. To resolve the problem of using the sprintf() function, the snprintf() is brought to the C library to make the program safer and more elegant. In this article, we discussed the snprintf() function in the examples provided.

About the author

Bamdeb Ghosh

Bamdeb Ghosh is having hands-on experience in Wireless networking domain.He's an expert in Wireshark capture analysis on Wireless or Wired Networking along with knowledge of Android, Bluetooth, Linux commands and python. Follow his site: wifisharks.com