c语言snprintf,snprintf()函数使用总结

函数描述

C库函数int snprintf(char * str, size_t size, const char * format, ...)

step1:将可变参数...按照format格式化成字符串;

step2:将step1得到的字符串写到str中,写多长呢?长度为size而且size包含\0

函数声明

int snprintf(char *str, size_t size, const char *format, ...)

函数入参

str -- 目标字符串。

size -- 拷贝字节数(Bytes),长度包含\0。

format -- 格式化成字符串。

... -- 可变参数。

返回值

(1) 如果格式化后的字符串长度小于 size,则会把字符串全部复制到 str 中,并给其后添加一个字符串结束符 \0;

(2) 如果格式化后的字符串长度大于等于 size,超过 size-1 的部分会被截断,只将其中的 (size-1) 个字符复制到 str 中,并给其后添加一个字符串结束符 \0,返回值为欲写入的字符串长度。

example:

#include

#include

#include

void main()

{

char *str = (char *)malloc(20 * sizeof(char));

int ret = snprintf(str, 10, "123456789");

printf("str is [%s] and ret is [%d]\n", str, ret);

int ret1 = snprintf(str, 10, "1234567890");

printf("str is [%s] and ret1 is [%d]\n", str, ret1);

int ret2 = snprintf(str, 10, "12345678901");

printf("str is [%s] and ret2 is [%d]\n", str, ret2);

}

[root@localhost test]# gcc -Og test_snprintf.c -o proc

[root@localhost test]# ./proc

str is [123456789] and ret is [9]

str is [123456789] and ret1 is [10]

str is [123456789] and ret2 is [11]

#include

#include

#include

void main()

{

int i = 10;

char *str = malloc(i);

int ret = snprintf(str, 12, "1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890");

printf("str is [%s] and ret is[%d] \n", str, ret);

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值