C/Linux 中的 sprintf() 函数

sprintf() 函数属于 printf() 函数族。 在这个模块中,我们将发现更多关于这个函数的信息,以及我们如何在我们的程序中使用它。

定义 sprintf() 函数

Linux 手册页 对于 sprintf() 将其定义为:

#include <stdio.h> int sprintf(char *str, const char *format, ...); 

基本上 sprintf() 代表“字符串打印”。 与写入 stdout 的标准 printf() 不同,sprintf 将输出存储在提供给它的字符缓冲区中。 让我们稍微分解一下定义。

  • int – 你可能注意到的第一件事是 int 在我们函数定义的开头,它指的是函数的返回类型,可用于编程过程中的错误处理! 手册页描述了 返回值 的功能为:
Upon successful return, the functions return the number of characters printed (excluding the null byte used to end output to strings).  If an output error is encountered, a negative value is returned. 
  • 冲刺 – 函数名称!
  • 字符 *str – 这是一个指向存储结果字符串的字符数组的指针
  • const 字符 * 格式 – 这包含要写入缓冲区的字符串。 这也支持使用 格式说明符 在 C 中以获得更全面的结果并将它们存储到缓冲区中。

sprintf() 的示例实现

#include <stdio.h> void main() { 	char buffer[20]; 	sprintf(buffer,"The Buffer Size Is : %dn",sizeof(buffer)); 	printf("%s",buffer); } 

输出 :

The Buffer Size Is : 20 

解释输出

  • 首先我们声明包含定义的头文件 sprintf() 作为 :
#include <stdio.h> 
  • 接下来我们通过名称声明一个字符数组 ‘缓冲’ 存储我们的字符串:
char buffer[20]; 
  • 现在,我们可以调用我们的 sprintf() 功能。 在这里,为了演示格式说明符的使用,我们将使用 %d 显示缓冲区大小的格式说明符
sprintf(buffer,"The Buffer Size Is : %dn",sizeof(buffer)); 
  • 最后使用打印存储在缓冲区中的字符串 打印输出()
printf("%s",buffer); 

错误

手册页列出了有关 sprintf 的以下内容

Because sprintf() and vsprintf() assume  an  arbitrarily  long  string,callers must be careful not to overflow the actual space; this is often impossible to assure. Note that the length of the strings produced is locale-dependent  and  difficult  to  predict 

除此之外,它也容易受到 格式化字符串漏洞 因此,必须进行适当的检查以防止出现意外结果。

结论

因此,在本模块中:

  1. 过去的定义 sprintf(..) 功能
  2. 讨论函数采用的参数类型
  3. 我们甚至制定了一个例子
  4. 最后,我们讨论了一些常见的错误

我们的模块到此结束 sprintf() 功能。 感谢您的阅读!