_snprintf()與sprintf()的區別

_snprintf()

函數功能:將格式化的數據寫入字符串。
函數原型:
int _snprintf(
   char *buffer,
   size_t count,
   const char *format [,
   argument] ... 
);

參數:
buffer:輸出的存儲位置。
count:可存儲的最多字符數。
format::窗體控件字符串。
argument:可選參數。

返回值:
將 len 設爲格式化數據字符串的長度,不包括終止 null。

如果 len < count,len 個字符將存儲在 buffer 中,附加 null 終止符,並返回 len。
如果 len = count,len 個字符將存儲在 buffer 中,不附加 null 終止符,並返回 len。
如果 len > count,count 個字符將存儲在 buffer 中,不附加 null 終止符,並返回負值。


#include<iostream>
#include<cstdio>

using namespace std;

int main()
{
	//測試_snprintf()
	char str[5];

	int n=_snprintf(str,sizeof(str),"12345%s","lanzhihui");//因爲sizeof(str)小於源字符串,所以不會複製'\0'給數組str,

	str[sizeof(str)-1]='\0';//如果缺少此句,輸出亂碼

	cout<<"source strings :"<<n<<endl;//返回負數
	puts(str);     

	char str_1[50];

	n=_snprintf(str_1,sizeof(str_1),"lanzhihui%s"," is a good boy!");//因爲sizeof(str_1)大於源字符串,所以會複製'\0'給數組str_1

	cout<<"source strings :"<<n<<endl;
	puts(str_1);


	//測試sprintf()
	char str_2[5];

	n=sprintf(str_2,"12345%s","lanzhihui");//因爲sizeof(str_2)小於源字符串,所以不會複製'\0'給數組str,
                                               //此句導致程序崩潰  
	//str[sizeof(str)-1]='\0';//sprintf始終會在字符串末尾添加結束符

	cout<<"source strings :"<<n<<endl;
	puts(str_2);

	char str_3[50];

	cout<<"source strings :"<<n<<endl;
	n=sprintf(str_3,"lanzhihui%s"," is a good boy!");//因爲sizeof(str_3)大於源字符串,所以會複製'\0'給數組str_3

	puts(str_3);

	system("pause");
	return 0;
}

得出的結論:

1. windows上無snprintf,但是有_snprintf可以達到同樣的功能,但是細節之處略有不同 
2. 未溢出時,sprintf和snprintf都會在字符串末尾加上'\0'; 
3. 超出緩衝區大小時,_snprintf不會造成溢出,只是不會在緩衝區中添加字符結束符 
4. sprintf始終會在字符串末尾添加結束符,但是存在緩衝區溢出的情況 
5. _snprintf比sprintf安全,即不會造成緩衝區溢出 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章