我最近最佳化一個Linux-C小程式,用snprintf()函數往數組(或字串)裡寫入資料。我不用sprintf()是因為它不夠安全,不小心就會記憶體溢出,導致“段錯誤”!我認識並使用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! 上面的內容還說,如果傳回值等於或者大於size,則表明輸出字串被截斷了(truncated)。
各位~注意啦~ 原文地址:http://snailwarrior.blog.51cto.com/680306/152913