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
返回 * 如果转换在未写入空字符的情况下停止,则函数将在
dst
中的下一个字节中存储 '\0',这可能是 dst[len]
或 dst[dstsz]
,以先到者为准(意味着最多可能写入 len+1/dstsz+1 个总字节)。在这种情况下,在终止 null 之前可能没有写入取消移位序列。 * 如果
dst
是空指针,则将生成的字节数存储在 *retval 中 * 函数会覆盖目标数组,从终止 null 到
dstsz
* 如果
src
和 dst
重叠,则行为未定义。 * 在运行时检测到以下错误,并调用当前安装的 约束处理函数
-
retval
或src
是空指针 -
dstsz
或len
大于 RSIZE_MAX(除非dst
为空) -
dstsz
不为零(除非dst
为空) -
len
大于dstsz
,并且在到达dstsz
时,转换未在src
数组中遇到 null 或编码错误(除非dst
为空)
-
- 与所有边界检查函数一样,只有当实现定义了 __STDC_LIB_EXT1__ 并且用户在包含 <stdlib.h> 之前将 __STDC_WANT_LIB_EXT1__ 定义为整数常量 1 时,才能保证
wcstombs_s
可用。
目录 |
[编辑] 注解
在大多数实现中,wcstombs
在处理字符串时更新 mbstate_t 类型的全局静态对象,并且不能被两个线程同时调用,在这种情况下应使用 wcsrtombs 或 wcstombs_s
。
POSIX 指定了一个常见的扩展:如果 dst
是一个空指针,则此函数返回如果转换将写入 dst
的字节数。类似的行为对于 wcsrtombs 和 wcstombs_s
是标准的。
[编辑] 参数
dst | - | 指向将存储多字节字符的窄字符数组的指针 |
src | - | 指向要转换的空终止宽字符串的第一个元素的指针 |
len | - | dst 指向的数组中可用的字节数 |
dstsz | - | 将写入的最大字节数(dst 数组的大小) |
retval | - | 指向将存储结果的 size_t 对象的指针 |
[编辑] 返回值
2) 成功时返回零(在这种情况下,写入或将要写入
dst
的字节数(不包括终止零)存储在 *retval 中),错误时返回非零值。如果发生运行时约束冲突,则在 *retval 中存储 (size_t)-1(除非 retval
为空),并将 dst[0] 设置为 '\0'(除非 dst
为空或 dstmax
为零或大于 RSIZE_MAX)[编辑] 示例
运行此代码
#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