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會自動將\0加入到str中,

snprintf的返回值是實際str的長度

case 2 : 如果要輸出的字符串長度>= size, 則表明str的長度不夠寫入原有的長度,則snprintf的返回值

在理想情況下(即str的長度足夠長)的字符串長度,所以其返回值可能會出現>= size的情況。

另外需要說明的snprintf會自動將’\0′追加到str的末尾,而snprintf的返回值是不包括’\0′的

這個在官方的manual里寫的比較清楚:

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. (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.失敗了,返回一個負數。

但說明情況下返回負數呢?特殊情況下,就會緩沖區溢出了,並不能返回負數?

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM