snprintf()函数使用总结

2021-01-06  本文已影响0人  EamonXia

函数描述

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

函数声明

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

函数入参

返回值

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

example:

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

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 <stdlib.h>
#include <stdio.h>
#include <string.h>

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);
}


上一篇 下一篇

猜你喜欢

热点阅读