snprintf 返回值

在平时写代码的过程中,我一个推荐带有n系列的字符串函数,如

strcat ->strncat

sprintf->snprintf

我们有类似的一个函数

void dump_kid(std::string* str, uint32_t kid)
{
  char buffer[16];
  int len;                                                                                                                  
  if (str->empty())
  {   
    len = snprintf(buffer,sizeof(buffer), "%u", kid);
  }   
  else
  {   
    len = snprintf(buffer,sizeof(buffer), ",%u", kid);
  }   
  str->append(buffer, len);
}

我们知道,string的append可以接受没有长度的char*,但这样的效率不高,其内部也会strlen一下。

所以,在此处我们利用了snprintf的返回值,但查了下,snprintf的返回值有个陷阱。

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.

而sprintf的说明

On success, the total number of characters written is returned. This count does not include the additional null-character automatically appended at the end of the string.

成功返回写字符的总数,其中不包括结尾的null字符。
On failure, a negative number is returned.失败了,返回一个负数。

但说明情况下返回负数呢?特殊情况下,就会缓冲区溢出了,并不能返回负数?

原文地址:https://www.cnblogs.com/westfly/p/3812155.html