strncpy_s, _strncpy_s_l, wcsncpy_s, _wcsncpy_s_l, _mbsncpy_s, _mbsncpy_s_l

Copia i caratteri di una stringa in un'altra. Queste versioni di strncpy, _strncpy_l_wcsncpy_lwcsncpy, _mbsncpy, _mbsncpy_l includono miglioramenti della sicurezza, come descritto in Funzionalità di sicurezza in CRT.

Importante

_mbsncpy_s e _mbsncpy_s_l non possono essere usati nelle applicazioni eseguite in Windows Runtime. Per altre informazioni, vedere Funzioni CRT non supportate nelle app della piattaforma UWP (Universal Windows Platform).

Sintassi

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

Parametri

strDest
Stringa di destinazione.

numberOfElements
Dimensioni della stringa di destinazione, in caratteri.

strSource
Stringa di origine.

count
Numero di caratteri da copiare o _TRUNCATE.

locale
Impostazioni locali da usare.

Valore restituito

Zero in caso di esito positivo, STRUNCATE in caso di troncamento e un codice di errore negli altri casi.

Condizioni di errore

strDest numberOfElements strSource Valore restituito Contenuto di strDest
NULL qualsiasi qualsiasi EINVAL non modificato
qualsiasi qualsiasi NULL EINVAL strDest[0] impostato su 0
qualsiasi 0 qualsiasi EINVAL non modificato
non NULL troppo piccolo qualsiasi ERANGE strDest[0] impostato su 0

Osservazioni:

Queste funzioni tentano di copiare i primi D caratteri di strSource in strDest, dove D è il minore di count e la lunghezza di strSource. Se tali D caratteri rientrano strDest (le cui dimensioni vengono specificate come numberOfElements) e lasciano spazio per un terminatore Null, tali caratteri vengono copiati e viene aggiunto un valore Null che termina; in caso contrario, strDest[0] viene impostato sul carattere Null e viene richiamato il gestore di parametri non validi, come descritto in Convalida dei parametri.

Esiste un'eccezione al paragrafo precedente. Se count è _TRUNCATE, viene copiato gran parte di strSource come verrà strDest copiato pur lasciando spazio per il valore Null di terminazione, che viene sempre accodato.

Ad esempio,

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

significa che strncpy_s copia cinque caratteri in un buffer a 5 byte. Questa copia non lascia spazio per il carattere di terminazione Null, quindi strncpy_s zero la stringa e chiama il gestore di parametri non validi.

Se è necessario un comportamento di troncamento, usare _TRUNCATE o (size - 1):

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

A differenza di strncpy, se count è maggiore della lunghezza di , la stringa di strSourcedestinazione NON viene riempita con caratteri Null fino a lunghezza count.

Se le stringhe di origine e di destinazione si sovrappongono, il comportamento di strncpy_s non è definito.

Se strDest o strSource è NULL o numberOfElements è 0, viene richiamato il gestore di parametri non validi. Se l'esecuzione può continuare, la funzione restituisce EINVAL e imposta errno su EINVAL.

wcsncpy_s e _mbsncpy_s sono versioni con caratteri wide e caratteri multibyte di strncpy_s. Gli argomenti e il valore restituito di wcsncpy_s e mbsncpy_s variano di conseguenza. In alternativa queste sei funzioni si comportano in modo identico.

Il valore di output è interessato dall'impostazione dell'impostazione LC_CTYPE della categoria delle impostazioni locali. Per ulteriori informazioni, vedere setlocale. Le versioni di queste funzioni senza il suffisso _l usano le impostazioni locali correnti per questo comportamento dipendente dalle impostazioni locali. Le versioni con il suffisso _l sono identiche ma usano il parametro passato relativo alle impostazioni locali. Per altre informazioni, vedere Locale.

In C++ l'utilizzo di queste funzioni è semplificato dagli overload dei modelli. Gli overload possono dedurre la lunghezza del buffer automaticamente (eliminando la necessità di specificare un argomento di dimensione) e possono sostituire automaticamente le funzioni precedenti e non sicure con le controparti più recenti e sicure. Per altre informazioni, vedere Proteggere gli overload dei modelli.

Le versioni della libreria di debug di queste funzioni riempiono prima di tutto il buffer con 0xFE. Per disabilitare questo comportamento, usare _CrtSetDebugFillThreshold.

Per impostazione predefinita, lo stato globale di questa funzione è limitato all'applicazione. Per modificare questo comportamento, vedere Stato globale in CRT.

Mapping di routine di testo generico

TCHAR.H Routine _UNICODE e _MBCS non definito _MBCS Definito _UNICODE Definito
_tcsncpy_s strncpy_s _mbsnbcpy_s wcsncpy_s
_tcsncpy_s_l _strncpy_s_l _mbsnbcpy_s_l _wcsncpy_s_l

Nota

_strncpy_s_le _wcsncpy_s_l_mbsncpy_s_l non hanno alcuna dipendenza dalle impostazioni locali. Vengono forniti solo per _tcsncpy_s_l e non sono destinati a essere chiamati direttamente.

Requisiti

Ciclo Intestazione obbligatoria
strncpy_s, _strncpy_s_l <string.h>
wcsncpy_s, _wcsncpy_s_l <string.h> oppure <wchar.h>
_mbsncpy_s, _mbsncpy_s_l <mbstring.h>

Per altre informazioni sulla compatibilità, vedere Compatibility (Compatibilità).

Esempio: Copiare caratteri in un buffer

// 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: ''

Esempio: strncpy e 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'

Vedi anche

Manipolazione delle stringhe
impostazioni locali
Interpretazione di sequenze di caratteri multibyte
_mbsnbcpy, _mbsnbcpy_l
strcat_s, wcscat_s, _mbscat_s
strcmp, wcscmp, _mbscmp
strcpy_s, wcscpy_s, _mbscpy_s
strncat_s, _strncat_s_l, wcsncat_s, _wcsncat_s_l, _mbsncat_s, _mbsncat_s_l
strncmp, wcsncmp, _mbsncmp, _mbsncmp_l
_strnicmp, _wcsnicmp, _mbsnicmp, _strnicmp_l, _wcsnicmp_l, _mbsnicmp_l
strrchr, wcsrchr, _mbsrchr, _mbsrchr_l
_strset, _strset_l, _wcsset, _wcsset_l, _mbsset, _mbsset_l
strspn, wcsspn, _mbsspn, _mbsspn_l