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

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

cai_niaocainiao

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值