- 描述
C 库函数int snprintf(char *str, size_t size, const char *format, ...) 可变参数(...) 按照format 格式化成字符串, 并将字符串复制到str中,size为要写入的字符的最大数目,超过size会被截断。
- 声明
snprintf()函数的声明:
int snprintf(char * str, size_t size, const char * format, ...);
- 参数解析:
str -- 目标字符串
size -- 拷贝字节数(Bytes)
format -- 格式化成字符串
... -- 可变参数
- 返回值参数解析
如果格式化后的字符串长度小于等于size, 则会把字符串全部复制到str中,并给其后添加一个字符串结束符\0;
如果格式化后的字符串长度大于size, 超过size的部分会被截断,只将其中的(size-1)个字符复制到str中,并给其后添加一个字符串结束符\0, 返回值为欲写入的字符串长度。
- 实例1:格式化字符串
#include <stdio.h>
int main()
{
int j = 0;
char buffer[50] = {0};
char s[] = {"helloworld"};
j = snprintf(buffer, 6, "%s\n", s);
/*print buffer*/
printf("string: %s\n", buffer);
/*print character count*/
printf("character count:%d\n", j);
return 0;
}
string: hello
character count: 11
snprintf(buffer, 6, "%s\n", s); 表示将字符串s中的前6个字节拷贝到buffer数组中,字符串s将被截断,最后一个字节被'\0' 占据,所以当拷贝字节数为6个字节时,格式化后的buffer为hello。
- 实例2: 将字符串和数字组合成一个新的字符串
char str[ ] = "testsnprintf";
char node[30] = {0};
snprintf(node, sizeof(node), "%s-%d-%d", str, 11, 11);
printf("==>UDEBUG node = %s\n", node);
- 实例3: 将两个字符串组合成一个新的字符串
char str1[ ] = "hello";
char str2[ ] = "world";
char node[30] = {0};
snprintf(node, sizeof(node), "%s %s", str1, str2);
printf("==>UDEBUG strlen(node) = %ld\n", strlen(node));
printf("==>UDEBUG node = %s\n", node);
- 实例4: 组合需要使用的linux 命令
char tmpBuf[256] = {0};
snprintf(tmpBuf, sizeof(tmpBuf), "cp %s %s", "param1", "param2");
printf("tmpBuf = %s\n", tmpBuf);
snprintf(tmpBuf, sizeof(tmpBuf), "cp %s %s", "param3", "param4");
printf("tmpBuf = %s\n", tmpBuf);
snprintf(tmpBuf, sizeof(tmpBuf), "mkdir %s %s", "-p", "/var/cfg/");
printf("tmpBuf = %s\n", tmpBuf);
- 实例5:输出特定格式字符串
char node[ ] = "HELLO";
char nodeName[32] = {0};
snprintf(nodeName, sizeof(nodeName), "[%s]", node);
printf("==>UDEBUG nodeName = %s\n", nodeName);
snprintf(nodeName, sizeof(nodeName), "%d-%d", 11, 11);
printf("==>UDEBUG nodeName = %s\n", nodeName);