sprintf_s、_snprintf与_snprintf_s的用法

sprintf_s

函数功能:将数据格式化输出到字符串 函数原型:

  int sprintf_s(  

      char *buffer,   //存储位置

  size_t sizeOfBuffer, //最大允许的字符数

 const char *format [,  argument] ...

  );

需要包含的头文件:stdio.h

注意:

sprintf_s()是sprintf()的安全版本,通过指定缓冲区长度来避免sprintf()存在的溢出风险

程序示例:(软件;vs2013)

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
	char file[110];  //需要预先分配缓冲区
	char path[30] = "Hello!";
	sprintf_s(file, 110,"%s", path);
	printf("%s\n", file);
	system("pause");
	return 0;
}

结果;Hello!

snprintf(注:在dev5.4.0里能运行,在vs2013里不能运行,只能运行_sprintf)

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

函数说明:最多从源串中拷贝n-1个字符到目标串中,然后再在后面加一个0。所以如果目标串的大小为n 的话,将不会溢出。

函数返回值:若成功则返回欲写入的字符串长度,若出错则返回负值。

#include <stdio.h>
#include <stdlib.h>

int main()
{
     char str[10]={0,};
     snprintf(str, sizeof(str ) , "0123456789012345678");
     printf("str=%s\n", str);
     return 0;
}

结果:str=012345678

_snprintf:

示例:(软件vs2013)

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#pragma warning(disable:4996)
int main()
{


	char str[10] = { 0, };
	_snprintf(str, sizeof(str)-1, "0123456789a");
	printf("str=%s\n", str);
	system("pause");
	return 0;
}

结果:012345678

 _snprintf_s

_snprintf_s()函数的n代表最多复制多少个字符,函数名尾部_s表示检测缓冲区溢出,微软特有的检测。

示例:(软件vs2013)

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{

	char str[] = "abcdefghijklmnopqrstuvw";
	char file[10] = { 0 };
	//将会崩溃,因为会发生缓冲区溢出  
	//_snprintf_s(file, sizeof(file), "%s", str);  
	//正确用法  
	_snprintf_s(file, sizeof(file)-1, "%s", str);
	printf("%s\n", file);
	system("pause");
	return 0;
}

结果:abcdefghi

猜你喜欢

转载自blog.csdn.net/cai_niaocainiao/article/details/82109821