函數(shù)描述
C庫函數(shù)int snprintf(char * str, size_t size, const char * format, ...)
- step1:將可變參數(shù)
...
按照format
格式化成字符串瘪吏; - step2:將step1得到的字符串寫到
str
中,寫多長呢晤硕?長度為size
而且size
包含\0
函數(shù)聲明
int snprintf(char *str, size_t size, const char *format, ...)
函數(shù)入?yún)?/h4>
-
str
-- 目標字符串性置。
-
size
-- 拷貝字節(jié)數(shù)(Bytes)捻浦,長度包含\0
缠捌。
-
format
-- 格式化成字符串英染。
-
...
-- 可變參數(shù)搪锣。
返回值
str
-- 目標字符串性置。size
-- 拷貝字節(jié)數(shù)(Bytes)捻浦,長度包含\0
缠捌。format
-- 格式化成字符串英染。...
-- 可變參數(shù)搪锣。(1) 如果格式化后的字符串長度小于 size丢郊,則會把字符串全部復制到 str 中盔沫,并給其后添加一個字符串結(jié)束符 \0医咨;
(2) 如果格式化后的字符串長度大于等于 size,超過 size-1 的部分會被截斷架诞,只將其中的 (size-1) 個字符復制到 str 中拟淮,并給其后添加一個字符串結(jié)束符 \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);
}