1、原型

   #include <stdio.h>

   int printf(const char *format, ...);
   int fprintf(FILE *stream, const char *format, ...);
   int sprintf(char *str, const char *format, ...);
   int snprintf(char *str, size_t size, const char *format, ...);

   #include <stdarg.h>

   int vprintf(const char *format, va_list ap);
   int vfprintf(FILE *stream, const char *format, va_list ap);
   int vsprintf(char *str, const char *format, va_list ap);
   int vsnprintf(char *str, size_t size, const char *format, va_list ap);

2、使用实例

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

#define BUFLEN 4
char *a = "";
char *b = "345";

int main(int argc,char **argv)
{
    int ret = 0;
    int len = 0;
    char buf[BUFLEN]={0};

    ret = snprintf(buf+len,BUFLEN-len,"%s",a);
    printf("ret: %d buf:%s\n",ret,buf);
    if(ret >=0)
    {
        len+= ret;
        ret = snprintf(buf+len,BUFLEN-len,"%s",b);
        len += ret;
        if(ret <0 || ret +len >= BUFLEN)
        {
            buf[BUFLEN-1]='\0';
            len = BUFLEN-1;
        }
    }
    else
    {
        buf[BUFLEN-1]='\0';
        len = BUFLEN-1;
    }
    printf("ret: %d buf:%s len:%d len(buf):%d\n",ret,buf,len,strlen(buf));
    while(1);

    return 0;
}

3、运行结果

(1)snprintf返回值为0

char *a = "";
char *b = "345";

当BUFLEN==4,上述条件下运行结果为:

ret: 0 buf:
ret: 3 buf:345 len:3 len(buf):3

ret = snprintf(buf+len,BUFLEN-len,"%s",a);执行返回值为0;

(2)snprintf返回值为-1

char *a = "12";
char *b = "345";

当BUFLEN==4,上述条件下运行结果为:

ret: 2 buf:12
ret: 3 buf:123 len:3 len(buf):3

ret = snprintf(buf+len,BUFLEN-len,"%s",b);执行返回值为-1;

(3)snprintf返回值大于0

char *a = "1234";
char *b = "345";

当BUFLEN==4,上述条件下运行结果为:

ret: 4 buf:123
ret: 3 buf:123 len:3 len(buf):3

ret = snprintf(buf+len,BUFLEN-len,"%s",a);执行返回值为4,实际写入的大小为3;

4、分析

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

snprintf的返回值有四种:
(1)可用空间>填充大小时候返回填充的大小;
(2)填充大小为0时候返回0
(3)可用空间<填充大小时返回-1;
(4)可用空间=填充大小,此时返回值为填充大小,实际写入的大小为返回值-1;

5、程序附件

  [snprintf.c][1]