1. 程式人生 > >sprintf()函數 和 printf()函數

sprintf()函數 和 printf()函數

rest pos details 寫入 區別 應該 用法 使用 說明

sprintf()函數 和 printf()函數

參考:C++ 中的sprintf和snprintf 函數的區別 - CSDN博客 http://blog.csdn.net/youbingchen/article/details/51980640


sprintf()函數

int sprintf(char *string,char *format,arg_list);

函數sprintf()的用法和printf()函數一樣,只是sprintf()函數給出第一個參數string(一般為字符數組),然後再調用 outtextxy()函數將串裏的字符顯示在屏幕上。arg_list為參數表,可有不定個數。通常在繪圖方式下輸出數字時可調用sprintf()函 數將所要輸出的格式送到第一個參數,然後顯示輸出。

snprintf()函數

int snprintf(char *restrict buf, size_t n, const char * restrict format, ...);

函數說明:

最多從源串中拷貝n-1個字符到目標串中,然後再在後面加一個0。所以如果目標串的大小為n 的話,將不會溢出。

函數返回值:

若成功則返回欲寫入的字符串長度,若出錯則返回負值。

snprintf函數是sprintf的限制字符數量的一個表達。

sprintf函數返回的是實際輸出到字符串緩沖中的字符個數,包括null結束符。

snprintf函數返回的是應該輸出到字符串緩沖的字符個數,所以snprintf的返回值可能大於給定的可用緩沖大小以及最終得到的字符串長度

Example:

#include <stdio.h>

#include <stdlib.h>

int main()

{

     char str[10]={0,};

     snprintf(str, sizeof(str), "0123456789012345678");

     printf("str=%s/n", str);

     return 0;

}

總結

sprintf可能導致緩沖區溢出問題而不被推薦使用,所以在項目中我一直優先選擇使用snprintf函數,雖然會稍微麻煩那麽一點點。這裏就是sprintf和snprintf最主要的區別:snprintf通過提供緩沖區的可用大小傳入參數來保證緩沖區的不溢出,如果超出緩沖區大小則進行截斷。但是對於snprintf函數,還有一些細微的差別需要註意。

sprintf()函數 和 printf()函數