01 简介

02 printf()

03 snprintf()

snprintf() 函数 在 <stdio.h> 头文件中定义,用于以指定格式存储指定字符串直至指定长度。

1
int snprintf(char * s, size_t n, const char *format, …);

[!quote]
The snprintf() function is defined in the <stdio.h> header file and is used to store the specified string till a specified length in the specified format.
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.

3.1 Example

3.1.1 Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
// C program to demonstrate snprintf()
#include <stdio.h>

int main()
{
char buffer[50];
char* s = "ThomasXU";

// Counting the character and storing
// in buffer using snprintf
printf("Writing %s onto buffer"
" with capacity 6",
s);
int j = snprintf(buffer, 6, "%s\n", s);

// Print the string stored in buffer and
// character count
printf("\nString written on "
"buffer = %s", buffer);
printf("\nValue returned by "
"snprintf() method = %d\n", j);

return 0;
}

Output:

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

3.1.2 Example: MicroROS

1
2
3
4
5
6
7
std_msgs__msg__String pub_msg;
std_msgs__msg__String__init(&pub_msg);
const unsigned int PUB_MSG_CAPACITY = 20;
pub_msg.data.data = malloc(PUB_MSG_CAPACITY);
pub_msg.data.capacity = PUB_MSG_CAPACITY;
snprintf(pub_msg.data.data, pub_msg.data.capacity, "Hello World!%d", string_pub_value++);
pub_msg.data.size = strlen(pub_msg.data.data);