strncpy_s_strncpy_s_lwcsncpy_s_wcsncpy_s_l_mbsncpy_s_mbsncpy_s_l_tcsncpy_s_tcsncpy_s_l_tcsnccpy_s_tcsnccpy_s_l

文字列の文字を他の文字列にコピーします。 これらのバージョンのstrncpy_strncpy_lwcsncpy_wcsncpy_l_mbsncpy_mbsncpy_l、「CRT のSecurity 機能」で説明されているように、セキュリティが強化されています

重要

_mbsncpy_s および _mbsncpy_s_l は、Windows ランタイムで実行するアプリケーションでは使用できません。 詳細については、「ユニバーサル Windows プラットフォーム アプリでサポートされていない CRT 関数」を参照してください。

_tcsnccpy_s_tcsnccpy_s_l_tcsnccpy_s、および_tcsnccpy_s_lについては、Generic-text 関数のマッピングを参照してください。

構文

errno_t strncpy_s(
   char *strDest,
   size_t numberOfElements,
   const char *strSource,
   size_t count
);
errno_t _strncpy_s_l(
   char *strDest,
   size_t numberOfElements,
   const char *strSource,
   size_t count,
   _locale_t locale
);
errno_t wcsncpy_s(
   wchar_t *strDest,
   size_t numberOfElements,
   const wchar_t *strSource,
   size_t count
);
errno_t _wcsncpy_s_l(
   wchar_t *strDest,
   size_t numberOfElements,
   const wchar_t *strSource,
   size_t count,
   _locale_t locale
);
errno_t _mbsncpy_s(
   unsigned char *strDest,
   size_t numberOfElements,
   const unsigned char *strSource,
   size_t count
);
errno_t _mbsncpy_s_l(
   unsigned char *strDest,
   size_t numberOfElements,
   const unsigned char *strSource,
   size_t count,
   _locale_t locale
);
template <size_t size>
errno_t strncpy_s(
   char (&strDest)[size],
   const char *strSource,
   size_t count
); // C++ only
template <size_t size>
errno_t _strncpy_s_l(
   char (&strDest)[size],
   const char *strSource,
   size_t count,
   _locale_t locale
); // C++ only
template <size_t size>
errno_t wcsncpy_s(
   wchar_t (&strDest)[size],
   const wchar_t *strSource,
   size_t count
); // C++ only
template <size_t size>
errno_t _wcsncpy_s_l(
   wchar_t (&strDest)[size],
   const wchar_t *strSource,
   size_t count,
   _locale_t locale
); // C++ only
template <size_t size>
errno_t _mbsncpy_s(
   unsigned char (&strDest)[size],
   const unsigned char *strSource,
   size_t count
); // C++ only
template <size_t size>
errno_t _mbsncpy_s_l(
   unsigned char (&strDest)[size],
   const unsigned char *strSource,
   size_t count,
   _locale_t locale
); // C++ only

パラメーター

strDest
対象文字列。

numberOfElements
対象文字列のサイズ (文字数)。

strSource
ソース文字列。

count
コピーする文字数または _TRUNCATE

locale
使用するロケール。

戻り値

正常終了した場合はゼロ、切り捨てが行われた場合は STRUNCATE、それ以外の場合はエラー コード。

エラー条件

strDest numberOfElements strSource 戻り値 strDest の内容
NULL 任意 任意 EINVAL 変更されない
任意 任意 NULL EINVAL 0 に設定された strDest[0]
任意 0 任意 EINVAL 変更されない
NULL 以外 小さすぎる 任意 ERANGE 0 に設定された strDest[0]

解説

これらの関数は、D の最初の strSource 文字を strDest にコピーしようとします。このとき、Dcount より小さく、strSource と同じ長さです。 これらの D 文字が strDest 内に収まり (そのサイズが numberOfElementsとして指定されている) 場合でも、それらの文字はコピーされ、終端の null が追加されます。それ以外の場合は、 strDest[0] が null 文字に設定され、無効なパラメーター ハンドラーが呼び出されます ( パラメーター検証で説明します

上記の段落には例外があります。 count_TRUNCATE場合、strDestに収まる限り多くのstrSourceがコピーされ、常に追加される終端の null の領域が残ります。

たとえば、 にします。

char dst[5];
strncpy_s(dst, 5, "a long string", 5);

は、 strncpy_s が 5 文字を 5 バイト のバッファーにコピーすることを意味します。 このコピーでは null ターミネータの領域が残されないため、 strncpy_s は文字列をゼロにし、無効なパラメーター ハンドラーを呼び出します。

切り捨て動作が必要な場合は、次のように、_TRUNCATE を使用するか、size を 1 減算します。

strncpy_s(dst, 5, "a long string", _TRUNCATE);
strncpy_s(dst, 5, "a long string", 4);

strncpyとは異なり、countstrSourceの長さを超える場合、変換先の文字列は、長さcountまで null 文字で埋め込まれません。

コピー元とコピー先の文字列が重なり合っている場合の strncpy_s 関数の動作は未定義です。

strDest または strSourceNULL である場合、または numberOfElements が 0 の場合、無効なパラメーター ハンドラーが呼び出されます。 実行の継続が許可された場合、関数は EINVAL を返し、errnoEINVAL に設定します。

wcsncpy_s 関数と _mbsncpy_s 関数は、strncpy_s 関数のワイド文字バージョンとマルチバイト文字バージョンです。 wcsncpy_smbsncpy_s は、これに応じて引数と戻り値が異なります。 それ以外では、これらの関数の動作は同じです。

出力値は、ロケールの LC_CTYPE カテゴリ設定の設定によって影響を受けます。 詳細については、setlocaleを参照してください。 _l サフィックスが付いていないこれらの関数のバージョンでは、このロケールに依存する動作に現在のロケールを使用します。_l サフィックスが付いているバージョンは、渡されたロケール パラメーターを代わりに使用する点を除いて同じです。 詳細については、「 Locale」を参照してください。

C++ では、これらの関数の使用はテンプレートのオーバーロードによって簡素化されます。オーバーロードでは、バッファー長を自動的に推論できる (サイズの引数を指定する必要がなくなる) だけでなく、古くてセキュリティが万全ではない関数を新しく安全な関数に自動的に置き換えることができます。 詳細については、「セキュリティ保護されたテンプレート オーバーロード」を参照してください。

これらの関数のデバッグ ライブラリ バージョンでは、最初にバッファーを 0xFE で埋めます。 この動作を無効にするには、_CrtSetDebugFillThreshold を使用します。

既定では、この関数のグローバル状態の適用対象は、アプリケーションになります。 この動作を変更するには、「CRT でのグローバル状態」を参照してください。

汎用テキスト関数マッピング

tchar.h列の関数は、コンパイル時に定義されている文字セットに応じて、他の列の関数にマップされます。

tchar.h ルーチン _UNICODE_MBCS が定義されていない _MBCS が定義されている _UNICODE が定義されている
_tcsncpy_s strncpy_s _mbsnbcpy_s wcsncpy_s
_tcsncpy_s_l _strncpy_s_l _mbsnbcpy_s_l _wcsncpy_s_l
_tcsnccpy_s strncpy_s _mbsncpy_s _wcsncpy_s
_tcsnccpy_s_l _strncpy_s_l _mbsncpy_s_l _wcsncpy_s_l

Note

_strncpy_s_l_wcsncpy_s_l 、および _mbsncpy_s_l にはロケールに依存しません。 これらは _tcsncpy_s_l のみを目的として提供され、直接呼び出されるものではありません。

要件

ルーチンによって返される値 必須ヘッダー
strncpy_s, _strncpy_s_l <string.h>
wcsncpy_s, _wcsncpy_s_l <string.h> または <wchar.h>
_mbsncpy_s, _mbsncpy_s_l <mbstring.h>

互換性の詳細については、「 Compatibility」を参照してください。

例: char をバッファーにコピーする

// crt_strncpy_s_1.cpp
// compile with: /MTd

// these #defines enable secure template overloads
// (see last part of Examples() below)
#define _CRT_SECURE_CPP_OVERLOAD_STANDARD_NAMES 1
#define _CRT_SECURE_CPP_OVERLOAD_STANDARD_NAMES_COUNT 1

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <crtdbg.h>  // For _CrtSetReportMode
#include <errno.h>

// This example uses a 10-byte destination buffer.

errno_t strncpy_s_tester( const char * src,
                          int count )
{
   char dest[10];

   printf( "\n" );

   if ( count == _TRUNCATE )
      printf( "Copying '%s' to %d-byte buffer dest with truncation semantics\n",
               src, _countof(dest) );
   else
      printf( "Copying %d chars of '%s' to %d-byte buffer dest\n",
              count, src, _countof(dest) );

   errno_t err = strncpy_s( dest, _countof(dest), src, count );

   printf( "    new contents of dest: '%s'\n", dest );

   return err;
}

void Examples()
{
   strncpy_s_tester( "howdy", 4 );
   strncpy_s_tester( "howdy", 5 );
   strncpy_s_tester( "howdy", 6 );

   printf( "\nDestination buffer too small:\n" );
   strncpy_s_tester( "Hi there!!", 10 );

   printf( "\nTruncation examples:\n" );

   errno_t err = strncpy_s_tester( "How do you do?", _TRUNCATE );
   printf( "    truncation %s occur\n", err == STRUNCATE ? "did"
                                                       : "did not" );

   err = strncpy_s_tester( "Howdy.", _TRUNCATE );
   printf( "    truncation %s occur\n", err == STRUNCATE ? "did"
                                                       : "did not" );

   printf( "\nSecure template overload example:\n" );

   char dest[10];
   strncpy( dest, "very very very long", 15 );
   // With secure template overloads enabled (see #defines at
   // top of file), the preceding line is replaced by
   //    strncpy_s( dest, _countof(dest), "very very very long", 15 );
   // Instead of causing a buffer overrun, strncpy_s invokes
   // the invalid parameter handler.
   // If secure template overloads were disabled, strncpy would
   // copy 15 characters and overrun the dest buffer.
   printf( "    new contents of dest: '%s'\n", dest );
}

void myInvalidParameterHandler(
   const wchar_t* expression,
   const wchar_t* function,
   const wchar_t* file,
   unsigned int line,
   uintptr_t pReserved)
{
   wprintf(L"Invalid parameter handler invoked: %s\n", expression);
}

int main( void )
{
   _invalid_parameter_handler oldHandler, newHandler;

   newHandler = myInvalidParameterHandler;
   oldHandler = _set_invalid_parameter_handler(newHandler);
   // Disable the message box for assertions.
   _CrtSetReportMode(_CRT_ASSERT, 0);

   Examples();
}
Copying 4 chars of 'howdy' to 10-byte buffer dest
    new contents of dest: 'howd'

Copying 5 chars of 'howdy' to 10-byte buffer dest
    new contents of dest: 'howdy'

Copying 6 chars of 'howdy' to 10-byte buffer dest
    new contents of dest: 'howdy'

Destination buffer too small:

Copying 10 chars of 'Hi there!!' to 10-byte buffer dest
Invalid parameter handler invoked: (L"Buffer is too small" && 0)
    new contents of dest: ''

Truncation examples:

Copying 'How do you do?' to 10-byte buffer dest with truncation semantics
    new contents of dest: 'How do yo'
    truncation did occur

Copying 'Howdy.' to 10-byte buffer dest with truncation semantics
    new contents of dest: 'Howdy.'
    truncation did not occur

Secure template overload example:
Invalid parameter handler invoked: (L"Buffer is too small" && 0)
    new contents of dest: ''

例: strncpy および strncpy_s

// crt_strncpy_s_2.c
// contrasts strncpy and strncpy_s

#include <stdio.h>
#include <stdlib.h>

int main( void )
{
   char a[20] = "test";
   char s[20];

   // simple strncpy usage:

   strcpy_s( s, 20, "dogs like cats" );
   printf( "Original string:\n   '%s'\n", s );

   // Here we can't use strncpy_s since we don't
   // want null termination
   strncpy( s, "mice", 4 );
   printf( "After strncpy (no null-termination):\n   '%s'\n", s );
   strncpy( s+5, "love", 4 );
   printf( "After strncpy into middle of string:\n   '%s'\n", s );

   // If we use strncpy_s, the string is terminated
   strncpy_s( s, _countof(s), "mice", 4 );
   printf( "After strncpy_s (with null-termination):\n   '%s'\n", s );

}
Original string:
   'dogs like cats'
After strncpy (no null-termination):
   'mice like cats'
After strncpy into middle of string:
   'mice love cats'
After strncpy_s (with null-termination):
   'mice'

関連項目

文字列操作
ロケール
マルチバイト文字のシーケンスの解釈
_mbsnbcpy, _mbsnbcpy_l
strcat_swcscat_s_mbscat_s
strcmpwcscmp_mbscmp
strcpy_swcscpy_s_mbscpy_s
strncat_s_strncat_s_lwcsncat_s_wcsncat_s_l_mbsncat_s_mbsncat_s_l
strncmpwcsncmp_mbsncmp_mbsncmp_l
_strnicmp_wcsnicmp_mbsnicmp_strnicmp_l_wcsnicmp_l_mbsnicmp_l
strrchrwcsrchr_mbsrchr_mbsrchr_l
_strset_strset_l_wcsset_wcsset_l_mbsset_mbsset_l
strspnwcsspn_mbsspn_mbsspn_l