snprintf()函数返回值

函数原型:
int snprintf(char *str, size_t size, const char *format, ...);
 
size 的做用就是限制往str写入不超过size个字节(包括告终尾的'\0')。
由于sprintf()函数若是成功的话,返回成功写入的字节数(字符数),我就一直觉得snprintf()函数也是如此,也就是snprintf()函数不会返回大于size的整数。
 
看下面一段手册内容:
 
The functions snprintf() and vsnprintf() do not  write  more than size bytes (including the trailing ’\0’). If the output was truncated due to this limit then the return value is the number of  characters (not including the trailing ’\0’) 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.
 

若是输出由于size的限制而被截断,返回值将是“若是有足够空间存储,所 能输出的字符数(不包括字符串结尾的'\0')”,这个值和size相等或者比size大!也就是说,若是能够写入的字符串是 "0123456789ABCDEF"共16位,可是size限制了是10,这样 snprintf() 的返回值将会是 16 而不是 10函数

snprintf函数会自动的在结尾加上'\0', 无论size限制超过没有, 若是超过, 怎加上 '\0' 字符一共是size个。 this

 
上面的内容还说,若是返回值等于或者大于size,则代表输出字符串被截断了(truncated)。
相关文章
相关标签/搜索