strcpy_s、wcscpy_s、_mbscpy_s
复制字符串。 strcpy、wcscpy、_mbscpy 的这些版本如 CRT 中的安全功能 所述,其安全得到了增强。
重要
_mbscpy_s 不能用于在 Windows 运行时 中执行的应用程序。有关详细信息,请参见 CRT functions not supported with /ZW(CRT 函数不支持使用 /ZW)。
errno_t strcpy_s(
char *strDestination,
size_t numberOfElements,
const char *strSource
);
errno_t wcscpy_s(
wchar_t *strDestination,
size_t numberOfElements,
const wchar_t *strSource
);
errno_t _mbscpy_s(
unsigned char *strDestination,
size_t numberOfElements,
const unsigned char *strSource
);
template <size_t size>
errno_t strcpy_s(
char (&strDestination)[size],
const char *strSource
); // C++ only
template <size_t size>
errno_t wcscpy_s(
wchar_t (&strDestination)[size],
const wchar_t *strSource
); // C++ only
template <size_t size>
errno_t _mbscpy_s(
unsigned char (&strDestination)[size],
const unsigned char *strSource
); // C++ only
参数
strDestination
目标字符串缓冲区的位置。numberOfElements
目标字符串缓冲区的大小。strSource
Null 终止的源字符串缓冲区。
返回值
如果成功,则为零;否则为错误代码。
错误情况
strDestination |
numberOfElements |
strSource |
返回值 |
strDestination 的内容 |
---|---|---|---|---|
NULL |
any |
any |
EINVAL |
未修改 |
any |
any |
NULL |
EINVAL |
strDestination[0] 设置为 0 |
any |
0,或太小 |
any |
ERANGE |
strDestination[0] 设置为 0 |
备注
strcpy_s 函数将 strSource 的地址内容,包括终止 null 字符,复制到了 strDestination 指定的位置。 目标字符串必须足以容纳源字符串及其终止 null 字符。 如果源和目标字符串重叠,则 strcpy_s 的行为未定义。
wcscpy_s 是 strcpy_s 的宽字符版本;_mbscpy_s 是多字节字符版本。 参数和 wcscpy_s 的返回值是宽字符字符串;_mbscpy_s 的参数和返回值为多字节字符字符串。 否则这三个函数否则具有相同行为。
如果 strDestination 或 strSource 是空指针,或者如果目标字符串太小,则调用无效参数处理程序,如 参数验证 中所述。 如果允许继续执行,则当 strDestination 或 strSource 是 null 指针时,这些函数返回 EINVAL 并且将 errno 设置为 EINVAL,而当目标字符串太小时,这些函数将返回 ERANGE 并且将 errno 设置为 ERANGE。
成功执行时,目标字符串总是以 null 结尾。
在 C++ 中,使用这些函数由模板重载简化;重载可以自动推导出缓冲区长度,因而不再需要指定大小参数,并且它们可以自动用以更新、更安全的对应物替换旧的、不安全的函数。 有关详细信息,请参阅 安全模板重载。
这些函数的调试版本首先用 0xFE 填充缓冲区。 若要禁用此行为,请使用 _CrtSetDebugFillThreshold。
一般文本例程映射
TCHAR.H 例程 |
未定义 _UNICODE & _MBCS |
已定义 _MBCS |
已定义 _UNICODE |
---|---|---|---|
_tcscpy_s |
strcpy_s |
_mbscpy_s |
wcscpy_s |
要求
例程 |
必需的标头 |
---|---|
strcpy_s |
<string.h> |
wcscpy_s |
<string.h> 或 <wchar.h> |
_mbscpy_s |
<mbstring.h> |
有关其他兼容性信息,请参见兼容性。
示例
// crt_strcpy_s.cpp
// This program uses strcpy_s and strcat_s
// to build a phrase.
//
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
int main( void )
{
char string[80];
// using template versions of strcpy_s and strcat_s:
strcpy_s( string, "Hello world from " );
strcat_s( string, "strcpy_s " );
strcat_s( string, "and " );
// of course we can supply the size explicitly if we want to:
strcat_s( string, _countof(string), "strcat_s!" );
printf( "String = %s\n", string );
}
.NET Framework 等效项
请参见
参考
strncat_s、_strncat_s_l、wcsncat_s、_wcsncat_s_l、_mbsncat_s、_mbsncat_s_l
strncmp、wcsncmp、_mbsncmp、_mbsncmp_l
strncpy_s、_strncpy_s_l、wcsncpy_s、_wcsncpy_s_l、_mbsncpy_s、_mbsncpy_s_l
_strnicmp、_wcsnicmp、_mbsnicmp、_strnicmp_l、_wcsnicmp_l、_mbsnicmp_l