snprintf用法和注意

声明(cplusplus)

int snprintf ( char * s, size_t n, const char * format, ... );
/*
Parameters:
s
Pointer to a buffer where the resulting C-string is stored.
The buffer should have a size of at least n characters.

n
Maximum number of bytes to be used in the buffer.
The generated string has a length of at most n-1, leaving space for the additional terminating null character.
size_t is an unsigned integral type.

format
C string that contains a format string that follows the same specifications as format in printf (see printf for details).

... (additional arguments)
Depending on the format string, the function may expect a sequence of additional arguments, each containing a value to be used to replace a format specifier in the format string (or a pointer to a storage location, for n).
There should be at least as many of these arguments as the number of values specified in the format specifiers. Additional arguments are ignored by the function.
*/

Write formatted output to sized buffer.
Composes a string with the same text that would be printed if format was used on printf, but instead of being printed, the content is stored as a C string in the buffer pointed by s (taking n as the maximum buffer capacity to fill).

If the resulting string would be longer than n-1 characters, the remaining characters are discarded and not stored, but counted for the value returned by the function.

A terminating null character is automatically appended after the content written.

After the format parameter, the function expects at least as many additional arguments as needed for format.

将格式化输出写入大小缓冲区。

用与 printf 使用 format 时打印的文本相同的字符串组成字符串,但不是打印,而是将内容作为C字符串存储在由 s 指向的缓冲区中(以n为最大缓冲区填充容量)。

如果生成的字符串长度超过 n-1 个字符,则丢弃其余字符,不存储,而是将其计数为函数返回的值。

在写入内容后,将自动附加一个终止的空字符。

format参数之后,函数需要至少与 format 所需的 additional arguments 一样多。

Return Value

The number of characters that would have been written if n had been sufficiently large, not counting the terminating null character.
If an encoding error occurs, a negative number is returned.
Notice that only when this returned value is non-negative and less than n, the string has been completely written.

如果n足够大,则会写入的字符数,不包括终止的空字符。
如果发生编码错误,则返回负数。
请注意,只有当此返回值为非负值且小于n时,字符串才被完全写入。

Example

/* snprintf example */
#include <stdio.h>

int main ()
{
  char buffer [100];
  int cx;

  cx = snprintf ( buffer, 100, "The half of %d is %d", 60, 60/2 );

  if (cx>=0 && cx<100)      // check returned value

    snprintf ( buffer+cx, 100-cx, ", and the half of that is %d.", 60/2/2 );

  puts (buffer);

  return 0;
}

Output:

The half of 60 is 30, and the half of that is 15.

声明(msdn)

int snprintf(
   char *buffer,
   size_t count,
   const char *format [,
   argument] ...
);
int _snprintf(
   char *buffer,
   size_t count,
   const char *format [,
   argument] ...
);
/*
Parameters:
buffer
Storage location for the output.

count
Maximum number of characters to store.

format
Format-control string.

argument
Optional arguments.
*/

Return Value

Let len be the length of the formatted data string, not including the terminating null. Both len and count are the number of characters for snprintf and _snprintf, and the number of wide characters for _snwprintf.

For all functions, if len < count, len characters are stored in buffer, a null-terminator is appended, and len is returned.

The snprintf function truncates the output when len is greater than or equal to count, by placing a null-terminator at buffer[count-1]. The value returned is len, the number of characters that would have been output if count was large enough. The snprintf function returns a negative value if an encoding error occurs.

For all functions other than snprintf, if len = count, len characters are stored in buffer, no null-terminator is appended, and len is returned. If len > count, count characters are stored in buffer, no null-terminator is appended, and a negative value is returned.

If buffer is a null pointer and count is zero, len is returned as the count of characters required to format the output, not including the terminating null. To make a successful call with the same argument and locale parameters, allocate a buffer holding at least len + 1 characters.

If buffer is a null pointer and count is nonzero, or if format is a null pointer, the invalid parameter handler is invoked, as described in Parameter Validation. If execution is allowed to continue, these functions return -1 and set errno to EINVAL.

len为格式化数据字符串的长度,不包括终止null。lencount都是snprintf_snprintf的字符数,以及_snwprintf的宽字符数。

对于所有函数,如果len < count,则len个字符存储在buffer中,并附加空终止符,然后返回len

len >= count时,snprintf函数通过在 buffer[count-1]处放置空终止符来截断输出。
如果count足够大,返回的值是len,则会输出的字符数。如果发生编码错误,snprintf函数将返回负值。

对于除snprintf以外的所有函数,如果len=count,则len个字符存储在buffer中,不追加空终止符,并返回len
如果len>count,则count个字符存储在buffer中,不追加空终止符,并返回负值。

如果buffer是空指针且count为零,则返回len作为格式化输出所需的字符计数,不包括终止的null。要使用相同的参数和区域设置参数成功调用,请分配一个至少包含len+1个字符的缓冲区。

如果buffer是空指针且count非零,或者如果format是空指针,则调用无效的参数处理程序,如参数验证中所述。如果允许继续执行,这些函数将返回-1并将errno设置为EINVAL。

Remarks

The snprintf function and the _snprintf family of functions format and store count or fewer characters in buffer. The snprintf function always stores a terminating null character, truncating the output if necessary. The _snprintf family of functions only appends a terminating null character if the formatted string length is strictly less than count characters. Each argument (if any) is converted and is output according to the corresponding format specification in format. The format consists of ordinary characters and has the same form and function as the format argument for printf. If copying occurs between strings that overlap, the behavior is undefined.

snprintf 函数和 _snprintf 函数系列在缓冲区中格式化并存储 count 个数或更少的字符。snprintf函数始终存储一个终止的空字符NULL,必要时截断输出。如果格式化的字符串长度严格小于 count 个字符,则 _snprintf 系列函数只会附加一个终止的空字符。每个参数(如果有)都会转换,并根据format中相应的格式规范输出。格式由普通字符组成,与printfformat参数具有相同的形式和功能。如果复制发生在重叠的字符串之间,则行为未定义。

参考

cplusplus - snprintf
msdn - snprintf

### CAPL 中 `snprintf` 函数的用法 在 CANoe 编程环境中,CAPL 提供了多种字符串处理函数来帮助开发者更灵活地操作数据。其中,`snprintf` 是一个非常有用的函数,用于格式化输出到指定长度的字符数组。 #### 函数原型 ```c int snprintf(char *str, size_t n, const char *format, ...); ``` 此函数接受多个参数: - `char *str`: 输出缓冲区地址。 - `size_t n`: 要写入的最大字节数(包括终止符 `\0`)。 - `const char *format`: 格式控制串。 - 可变数量的附加参数,这些参数对应于格式串中的占位符[^1]。 #### 返回值说明 该函数返回实际写入的字符数(不计结尾处自动添加的空字符)。如果这个数目大于或等于 `n`,则表示由于空间不足而未完成整个转换过程;此时目标字符串不会被截断而是保持原样不变,并且会设置错误标志。 #### 使用示例 下面是一些具体的例子展示如何利用 `snprintf` 来构建动态消息: ##### 示例 1: 基本用法 当只需要简单替换变量时可以这样使用: ```capl variables { int value = 42; char buffer[50]; } on start{ snprintf(buffer,sizeof(buffer),"The answer is %d",value); } ``` 这段代码将会把 "The answer is 42" 存储至 `buffer` 数组内。 ##### 示例 2: 处理浮点数并限定精度 对于需要精确显示数值的情况,可以通过指定宽度小数点后的位数来进行调整: ```capl variables { float piValue = 3.14159f; char formattedPi[20]; } on start{ snprintf(formattedPi,sizeof(formattedPi),"%8.3f",piValue); } ``` 这里 `%8.3f` 表达的意思是在至少八个字符宽的空间里保留三位有效数字的小数部分打印出给定的圆周率近似值。 ##### 示例 3: 组合不同类型的数据 还可以在一个字符串中混合不同类型的输入项: ```capl variables { string name="World"; unsigned long timestamp=1672531200UL; // Unix 时间戳代表特定日期时间 char greetingMessage[100]=""; } on start{ snprintf(greetingMessage,sizeof(greetingMessage), "Hello %s! Current time since epoch:%lu", name, timestamp); } ``` 上述片段创建了一条问候语句,包含了文字常量、字符串以及整型变量的内容组合而成的新字符串
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值