wcstombs, wcstombs_s
来自 cppreference.cn
在头文件 <stdlib.h> 中定义 |
||
(1) | ||
(直到 C99) | ||
(C99 起) | ||
errno_t wcstombs_s( size_t *restrict retval, char *restrict dst, rsize_t dstsz, const wchar_t *restrict src, rsize_t len ); |
(2) | (C11 起) |
1) 将宽字符序列(其第一个元素由
src
指向)转换为其窄多字节表示,该表示以初始移位状态开始。转换后的字符存储在由 dst
指向的 char 数组的后续元素中。写入目标数组的字节数不超过 len
。 每个字符都像通过调用 wctomb 一样进行转换,只是 wctomb 的转换状态不受影响。如果发生以下情况,转换停止:
* 空字符 L'\0' 已转换并存储。在这种情况下存储的字节是解除移位序列(如果需要)后跟 '\0',
* 找到的 wchar_t 不对应于当前 C 区域设置中的有效字符。
* 要存储的下一个多字节字符将超过
len
。 如果
src
和 dst
重叠,则行为未指定。2) 与(1)相同,但:
* 函数通过输出参数
retval
返回其结果 * 如果转换在没有写入空字符的情况下停止,函数会将 '\0' 存储在
dst
中的下一个字节中,这可能是 dst[len]
或 dst[dstsz]
,以先到者为准(这意味着最多可以写入 len+1/dstsz+1 总字节)。在这种情况下,在终止空字符之前可能没有写入解除移位序列。 * 如果
dst
是空指针,则产生的字节数存储在 *retval 中 * 函数会从终止空字符到
dstsz
破坏目标数组 * 如果
src
和 dst
重叠,则行为未指定。 * 在运行时检测到以下错误并调用当前安装的 约束处理程序 函数
-
retval
或src
是空指针 -
dstsz
或len
大于 RSIZE_MAX(除非dst
为空) -
dstsz
不为零(除非dst
为空) -
len
大于dstsz
并且在达到dstsz
时,转换在src
数组中没有遇到空字符或编码错误(除非dst
为空)
-
- 与所有边界检查函数一样,只有当实现定义了 __STDC_LIB_EXT1__ 并且用户在包含 <stdlib.h> 之前将 __STDC_WANT_LIB_EXT1__ 定义为整数常量 1 时,才能保证
wcstombs_s
可用。
目录 |
[edit] 注意
在大多数实现中,wcstombs
在处理字符串时更新类型为 mbstate_t 的全局静态对象,并且不能由两个线程同时调用,在这种情况下应使用 wcsrtombs 或 wcstombs_s
。
POSIX 指定了一个常见扩展:如果 dst
是空指针,此函数返回如果转换,将写入 dst
的字节数。 wcsrtombs 和 wcstombs_s
的行为类似。
[edit] 参数
dst | - | 指向窄字符数组的指针,多字节字符将存储在此处 |
src | - | 指向要转换的空终止宽字符串的第一个元素的指针 |
len | - | dst 指向的数组中可用的字节数 |
dstsz | - | 将写入的最大字节数(dst 数组的大小) |
retval | - | 指向一个size_t对象的指针,结果将存储在此处 |
[edit] 返回值
2) 成功时返回零(在这种情况下,不包括终止零的字节数,已写入或将写入
dst
的字节数,存储在 *retval 中),错误时返回非零。如果发生运行时约束违规,则将 (size_t)-1 存储在 *retval 中(除非 retval
为空)并将 dst[0] 设置为 '\0' (除非 dst
为空或 dstmax
为零或大于 RSIZE_MAX)[edit] 示例
运行此代码
#include <stdio.h> #include <stdlib.h> #include <locale.h> int main(void) { // 4 wide characters const wchar_t src[] = L"z\u00df\u6c34\U0001f34c"; // they occupy 10 bytes in UTF-8 char dst[11]; setlocale(LC_ALL, "en_US.utf8"); printf("wide-character string: '%ls'\n",src); for (size_t ndx=0; ndx < sizeof src/sizeof src[0]; ++ndx) printf(" src[%2zu] = %#8x\n", ndx, src[ndx]); int rtn_val = wcstombs(dst, src, sizeof dst); printf("rtn_val = %d\n", rtn_val); if (rtn_val > 0) printf("multibyte string: '%s'\n",dst); for (size_t ndx=0; ndx<sizeof dst; ++ndx) printf(" dst[%2zu] = %#2x\n", ndx, (unsigned char)dst[ndx]); }
输出
wide-character string: 'zß水🍌' src[ 0] = 0x7a src[ 1] = 0xdf src[ 2] = 0x6c34 src[ 3] = 0x1f34c src[ 4] = 0 rtn_val = 10 multibyte string: 'zß水🍌' dst[ 0] = 0x7a dst[ 1] = 0xc3 dst[ 2] = 0x9f dst[ 3] = 0xe6 dst[ 4] = 0xb0 dst[ 5] = 0xb4 dst[ 6] = 0xf0 dst[ 7] = 0x9f dst[ 8] = 0x8d dst[ 9] = 0x8c dst[10] = 0
[edit] 参考
- C11 标准 (ISO/IEC 9899:2011)
- 7.22.8.2 wcstombs 函数 (p: 360)
- K.3.6.5.2 wcstombs_s 函数 (p: 612-614)