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)。
相關文章
相關標籤/搜索