sprintf和snprintf需要注意的地方

sprintf

int sprintf ( char * str, const char * format, ... );
Write formatted data to string
Composes a string with the same text that would be printed if  format was used on  printf, but instead of being printed, the content is stored as a  C string in the buffer pointed by  str.

The size of the buffer should be large enough to contain the entire resulting string (see  snprintf for a safer version). //buffer的大小必须能够包含format后形成的字符串的长度,不然会溢出。

A terminating null character is automatically appended after the content. //自动添加'\0'

After the  format parameter, the function expects at least as many additional arguments as needed for  format.

Parameters

str
Pointer to a buffer where the resulting C-string is stored.
The buffer should be large enough to contain the resulting string.
format
C string that contains a format string that follows the same specifications as  format in  printf (see  printf for details).
...  (additional arguments)
Depending on the  format string, the function may expect a sequence of additional arguments, each containing a value to be used to replace a  format specifier in the  format string (or a pointer to a storage location, for  n).
There should be at least as many of these arguments as the number of values specified in the  format specifiers. Additional arguments are ignored by the function.

Return Value

On success, the total number of characters written is returned. This count does not include the additional null-character automatically appended at the end of the string.
On failure, a negative number is returned.
返回值是形成字符串以后,该字符串的长度(不包括自动添加的空字符),例如下面的例子 "%d plus %d is %d"形成的字符串为" 5 plus 3 is 8 ",因此返回值为13。

Example

1
2
3
4
5
6
7
8
9
10
11
/* sprintf example */
#include <stdio.h>

int main ()
{
  char buffer [50];
  int n, a=5, b=3;
  n=sprintf (buffer, "%d plus %d is %d", a, b, a+b);
  printf ("[%s] is a string %d chars long\n",buffer,n);
  return 0;
}


Output:

[5 plus 3 is 8] is a string 13 chars long

snprintf

int snprintf ( char * s, size_t n, const char * format, ... );
Write formatted output to sized buffer
Composes a string with the same text that would be printed if  format was used on  printf, but instead of being printed, the content is stored as a  C string in the buffer pointed by  s (taking  n as the maximum buffer capacity to fill).

If the resulting string would be longer than n-1 characters, the remaining characters are discarded and not stored, but counted for the value returned by the function. //snprintf的返回值是欲写入的字符串长度,而不是实际写入的字符串长度

A terminating null character is automatically appended after the content written.

After the  format parameter, the function expects at least as many additional arguments as needed for  format.

Parameters

s
Pointer to a buffer where the resulting C-string is stored.
The buffer should have a size of at least  n characters.
n
Maximum number of bytes to be used in the buffer.
The generated string has a length of at most n-1, leaving space for the additional terminating null character. //最多拷贝n-1个字符
size_t is an unsigned integral type.
format
C string that contains a format string that follows the same specifications as  format in  printf (see  printf for details).
...  (additional arguments)
Depending on the  format string, the function may expect a sequence of additional arguments, each containing a value to be used to replace a  format specifier in the  format string (or a pointer to a storage location, for  n).
There should be at least as many of these arguments as the number of values specified in the  format specifiers. Additional arguments are ignored by the function.

Return Value

The number of characters that would have been written if  n had been sufficiently large, not counting the terminating  null character.
If an encoding error occurs, a negative number is returned.
Notice that only when this returned value is non-negative and less than  n, the string has been completely written.

Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
/* snprintf example */
#include <stdio.h>

int main ()
{
  char buffer [100];
  int cx;

  cx = snprintf ( buffer, 100, "The half of %d is %d", 60, 60/2 );

  if (cx>=0 && cx<100)      // check returned value

    snprintf ( buffer+cx, 100-cx, ", and the half of that is %d.", 60/2/2 );

  puts (buffer);

  return 0;
}


Output:
The half of 60 is 30, and the half of that is 15.

For more examples on formatting see  printf.


### 三、`sprintf` `snprintf` 的区别分析 在 C 语言中,`sprintf` `snprintf` 都用于将格式化的字符串输出到目标字符串中,它们的用法类似于 `printf`,但输出目标是字符串而非标准输出[^3]。然而,两者在行为安全性方面存在显著差异。 #### 3.1 缓冲区大小控制 `sprintf` 不检查目标缓冲区的大小,它会将格式化的字符串完整地写入目标字符串,直到遇到字符串结束符 `\0` 为止。这种行为可能导致缓冲区溢出,尤其是在目标缓冲区空间不足时。例如: ```c char buffer[10]; sprintf(buffer, "%s", "This string is too long"); // 缓冲区溢出风险 ``` 而 `snprintf` 多了一个参数 `n`,用于指定目标缓冲区的大小,它在写入时会限制最多写入 `n` 个字符(包括终止符 `\0`),从而有效防止缓冲区溢出。例如: ```c char buffer[10]; snprintf(buffer, sizeof(buffer), "%s", "This string is too long"); // 安全写入 ``` #### 3.2 返回值差异 `sprintf` 返回写入目标字符串的字符数(不包括终止符 `\0`)[^3]。这个返回值不能用于判断是否发生了缓冲区溢出。 `snprintf` 返回的是“将要写入”的字符数(不包括终止符),如果这个值大于或等于给定的缓冲区大小,则表示写入被截断。这一特性可以用于判断输出是否完整,从而增强程序的健壮性[^2]。 #### 3.3 安全性比较 由于 `sprintf` 不对缓冲区大小进行检查,它在使用不当的情况下容易引发缓冲区溢出问题,这在现代软件开发中被视为潜在的安全隐患。 相比之下,`snprintf` 在设计上更安全,因为它会确保写入的字符数不超过指定的缓冲区大小,从而避免溢出风险。因此,在需要将格式化字符串写入字符串的场景中,推荐优先使用 `snprintf`。 ### 总结 | 特性 | `sprintf` | `snprintf` | |------------------|----------------------------------|----------------------------------------| | 缓冲区大小控制 | 不检查,可能溢出 | 检查,防止溢出 | | 返回值含义 | 写入字符数(不含 `\0`) | 应写入字符数,可能被截断 | | 安全性 | 不安全,易引发溢出 | 安全,推荐使用 |
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值