int snprintf(char *restrict buf, size_t n, const char * restrict format, ...);
函数说明:最多从源串中拷贝n-1个字符到目标串中,然后再在后面加一个0。所以如果目标串的大小为n
的话,将不会溢出。
函数返回值:若成功则返回存入数组的字符数,若编码出错则返回负值。
Result1(推荐的用法)
1 #include <stdio.h>
2 #include <stdlib.h>
3
4 int main()
5 {
6
7 char str[10];
8 snprintf(str,sizeof(str),"0123456789012345678");
9 printf("str = %s /n",str);
10 return 0;
11 }
root@darkstar:/home/zhangl/unixtest/chapter9# ./testsprintf
str = 012345678
Result2:(不推荐使用)
1 #include <stdio.h>
2 #include <stdlib.h>
3
4 int main()
5 {
6
7 char str[10];
8 snprintf(str,18,"0123456789012345678");
9 printf("str = %s /n",str);
10 return 0;
11 }
root@darkstar:/home/zhangl/unixtest/chapter9# ./testsprintf
str = 01234567890123456
snprintf函数返回值的测试:
1 #include <stdio.h>
2 #include <stdlib.h>
3
4 int main()
5 {
6 char str[10];
7 int n=0;
8
9 n=snprintf(str,sizeof(str),"%s","abc");
10 printf("str = %s /n",str);
11 printf("n=%d/n",n);
12
13 return 0;
14 }
Result:
root@darkstar:/home/zhangl/test# ./testsnprintf
str = abc
n=3
函数说明:最多从源串中拷贝n-1个字符到目标串中,然后再在后面加一个0。所以如果目标串的大小为n
的话,将不会溢出。
函数返回值:若成功则返回存入数组的字符数,若编码出错则返回负值。
Result1(推荐的用法)
1 #include <stdio.h>
2 #include <stdlib.h>
3
4 int main()
5 {
6
7 char str[10];
8 snprintf(str,sizeof(str),"0123456789012345678");
9 printf("str = %s /n",str);
10 return 0;
11 }
root@darkstar:/home/zhangl/unixtest/chapter9# ./testsprintf
str = 012345678
Result2:(不推荐使用)
1 #include <stdio.h>
2 #include <stdlib.h>
3
4 int main()
5 {
6
7 char str[10];
8 snprintf(str,18,"0123456789012345678");
9 printf("str = %s /n",str);
10 return 0;
11 }
root@darkstar:/home/zhangl/unixtest/chapter9# ./testsprintf
str = 01234567890123456
snprintf函数返回值的测试:
1 #include <stdio.h>
2 #include <stdlib.h>
3
4 int main()
5 {
6 char str[10];
7 int n=0;
8
9 n=snprintf(str,sizeof(str),"%s","abc");
10 printf("str = %s /n",str);
11 printf("n=%d/n",n);
12
13 return 0;
14 }
Result:
root@darkstar:/home/zhangl/test# ./testsnprintf
str = abc
n=3