Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

C Library Function – snprintf()

C Library Function - snprintf()

C Standard Library - <stdio.h> C Standard Library -

Description

snprintf() is a standard C library function used to format and output a string, writing the result to a specified buffer. Unlike sprintf(), snprintf() limits the number of characters output to avoid buffer overflow.

The difference between sprintf() Unlike the function, the snprintf() function provides a parameter size that can prevent buffer overflow. If the length of the formatted string exceeds size-1, snprintf() will only write size-1 characters and add a null character (\0) at the end of the string to indicate its termination.

Declaration

Below is the declaration of the snprintf() function.


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

int snprintf(char str, size_t size, const char format, ...) Suppose the variable arguments(...)** according to format formatted into a string, and the string is copied to str in,size is the maximum number of characters to be written; exceeding size will be truncated, with at most size-1 characters written.

Parameters

Return Value

The return value is an integer:

Example

The following example demonstrates the use of the snprintf() function.

Example

#include

 

int

main

(

)

{

   

char

buffer

[

50

]

;

   

char

s

=

"runoobcom"

;

 

   

// read a string and store it in buffer

   

int

j

=

snprintf

(

buffer,

6

,

"%s\n"

, s

)

;

 

   

// output buffer and the character count

   

printf

(

"string:\n%s\ncharacter count = %d\n"

, buffer, j

)

;

 

   

return

0

;

}

The output is:

string:
runoo
character count = 10

The following is an example showing how to use the %f format specifier in snprintf() to output a single-precision floating-point number:

Example

#include

int

main

(

)

{

 

char

buffer

[

50

]

;

 

float

x

=

3.1415926

;

 

int

len

=

snprintf

(

buffer

,

50

,

"x = %f"

,

x

)

;

 

printf

(

"%s\n"

,

buffer

)

;

 

printf

(

"Written characters: %d\n"

,

len

)

;

 

return

0

;

}

The output is:


x = 3.141593
Written characters: 12

In the above example, snprintf() writes the string "x = 3.141593" into the buffer and returns the string length 12. Since the size of buffer is 50, there will be a null character at the end of the string. Finally, the program outputs the string in buffer and the character count returned by snprintf().

Notes:

In summary, when using the snprintf() function, you need to pay attention to issues such as buffer size, string terminator, format string, return value, and variable arguments to ensure correct output.

C Standard Library - <stdio.h> C Standard Library -