一聚教程网:一个值得你收藏的教程网站

最新下载

热门教程

C中snprintf函数的返回值问题

时间:2014-03-21 编辑:简简单单 来源:一聚教程网


今天特别记录下。

snprintf的函数原型为:
int snprintf(char *str, size_t size, const char *format, …);

说明:
之前以为snprintf的返回值是实际写入到str字符串的长度,其实不然

case 1 : 如果要输出的字符串的长度< size, 主要这里不包括=, 因为snprintf会自动将加入到str中,

snprintf的返回值是实际str的长度

case 2 : 如果要输出的字符串长度>= size, 则表明str的长度不够写入原有的长度,则snprintf的返回值

在理想情况下(即str的长度足够长)的字符串长度,所以其返回值可能会出现>= size的情况。

另外需要说明的snprintf会自动将’′追加到str的末尾,而snprintf的返回值是不包括’′的

这个在官方的manual里写的比较清楚:

If the output was truncated due to this limit then the return
value is the number of characters (not including the trailing ’’) which would have been written to the final string if  enough  space  had  been  available.
Thus,  a  return value of size or more means that the output was truncated. (See also below under NOTES.)  If an output error is encountered, a negative value
is returned.

看几个例子

Result1(推荐的用法)


#include
#include

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
#include

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
#include

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


解释SIZE:


#include
#include
int main()
{
char dst1[10] ={0, },dst2[10] ={0, };
char src1[10] ="aaa",src2[15] ="aaabbbcccddd";
int size=sizeof(dst1);
int ret1=0, ret2=0;
ret1=snprintf(dst1, size, "str :%s", src1);
ret2=snprintf(dst2, size, "str :%s", src2);
printf("sizeof(dst1)=%d, src1=%s, /"str :%%s/"=%s%s, dst1=%s, ret1=%d/n", sizeof(dst1), src1, "str :", src1, dst1, ret1);
printf("sizeof(dst2)=%d, src2=%s, /"str :%%s/"=%s%s, dst2=%s, ret2=%d/n", sizeof(dst2), src2, "str :", src2, dst2, ret2);
return 0;
}
root] /root/lindatest
$ ./test
sizeof(dst1)=10, src1=aaa, "str :%s"=str :aaa, dst1=str :aaa, ret1=8
sizeof(dst2)=10, src2=aaabbbcccddd, "str :%s"=str :aaabbbcccddd, dst2=str :aaab, ret2=17


补充一下,snprintf的返回值是欲写入的字符串长度,而不是实际写入的字符串度。如:
char test[8];
int ret = snprintf(test,5,"1234567890");
printf("%d|%s/n",ret,test);

运行结果为:
10|1234

 

热门栏目