//例子多点自然就懂了。
int snprintf(char *restrict buf, size_t n, const char * restrict format, ...);
函数说明:最多从源串中拷贝n-1个字符到目标串中,然后再在后面加一个0。所以如果目标串的大小为n
的话,将不会溢出。
函数返回值:若成功则返回欲写入的字符串长度,若出错则返回负值。
Result1(推荐的用法)
#include <stdio.h>
#include <stdlib.h>
int main()
{
char str[10]={0,};
snprintf(str, sizeof(str), "0123456789012345678");
printf("str=%s\n", str);
return 0;
}
root] /root/lindatest
$ ./test
str=012345678
Result2:(不推荐使用)
#include <stdio.h>
#include <stdlib.h>
int main()
{
char str[10]={0, };
snprintf(str, 18, "0123456789012345678");
printf("str=%s\n", str);
return 0;
}
root] /root/lindatest
$ ./test
str=01234567890123456
snprintf函数返回值的测试:
#include <stdio.h>
#include <stdlib.h>
int main()
{
char str1[10] ={0, };
char str2[10] ={0, };
int ret1=0,ret2=0;
ret1=snprintf(str1, sizeof(str1), "%s", "abc");
ret2=snprintf(str2, 4, "%s", "aaabbbccc");
printf("aaabbbccc length=%d\n", strlen("aaabbbccc"));
printf("str1=%s,ret1=%d\n", str1, ret1);
printf("str2=%s,ret2=%d\n", str2, ret2);
return 0;
}
[root] /root/lindatest
$ ./test
aaabbbccc length=9
str1=abc,ret1=3
str2=aaa,ret2=9
snprintf
int snprintf(char *str, size_t size, const char *format, ...);
将可变个参数(...)按照format格式化成字符串,然后将其复制到str中
(1) 如果格式化后的字符串长度 < size,则将此字符串全部复制到str中,并给其后添加一个字符串结束符('\0');
(2) 如果格式化后的字符串长度 >= size,则只将其中的(size-1)个字符复制到str中,并给其后添加一个字符串结束符('\0')
函数返回值:若成功则返回欲写入的字符串长度,若出错则返回负值。 --------------------------------------------
#include <stdio.h> //snprintf()
#include <string.h> //strlen()
int main()
{
char name[30];
char *name = "yangtaiping";
printf("strlen(name) = %d\n", strlen(name));
snprintf(name, strlen(name), "姓名:%s", name);
printf("name = %s\n", name);
printf("strlen(name) = %d\n", strlen(name));
}
strcpy() sprintf() strcat() 存在安全隐患, 其对应的安全版为:strncpy() snprintf() strncat() 。
snprintf(s, 100, "%.*S", 3, "abcd");s的值为abc %.*s 表示有两项, 第一项指定了长度,第二项则是%s的内容,所以取前三位 词条图册更多图册
Let len be the length of the formatted data string (not including the terminating null). len and count are in bytes for _snprintf, wide characters for _snwprintf.
If len < count, then len characters are stored in buffer, a null-terminator is appended, and len is returned.
If len = count, then len characters are stored in buffer, no null-terminator is appended, and len is returned.
If len > count, then count characters are stored in buffer, no null-terminator is appended, and a negative value is returned.
"如果字符串很长,超过了buffer的size,是否会截断后还是在buffer末尾添'\0'?"
If len > count, then count characters are stored in buffer, no null-terminator is appended, and a negative value is returned.
回答完毕。
以上是vc里ok,linux下的snprintf截断后会添加'\0',这个要注意。