Condividi tramite


strncpy_s, _strncpy_s_l, wcsncpy_s, _wcsncpy_s_l, _mbsncpy_s, _mbsncpy_s_l

I caratteri della copia di una stringa a un altro.Queste sono versioni di strncpy, _strncpy_l, wcsncpy, _wcsncpy_l, _mbsncpy, _mbsncpy_l con i miglioramenti della sicurezza come descritto in Funzionalità di sicurezza in CRT.

Nota importanteImportante

_mbsncpy_s e _mbsncpy_s_l non possono essere utilizzati nelle applicazioni eseguite nelle finestre runtime.Per ulteriori informazioni, vedere Funzioni CRT non supportate con /ZW.

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
    La dimensione della stringa di destinazione, in caratteri.

  • strSource
    Stringa di origine.

  • count
    Numero di caratteri da copiare, o _TRUNCATE.

  • locale
    Le impostazioni locali da utilizzare.

Valore restituito

Zero se l'operazione riesce, STRUNCATE se il troncamento si verifichi, altrimenti un codice di errore.

Condizioni di errore

strDest

numberOfElements

strSource

Valore restituito

Contenuti di strDest.

NULL

any

any

EINVAL

non modificato

any

any

NULL

EINVAL

Impostare strDest[0] a 0

any

0

any

EINVAL

non modificato

non NULL

troppo piccolo

any

ERANGE

Impostare strDest[0] a 0

Note

Queste funzioni consente di copiare i primi caratteri di D di strSource a strDest, dove le D è minore di count e la lunghezza di strSource.Se tali caratteri di D sarà necessario riavviare strDest (la cui dimensione viene fornita come numberOfElements) e successivamente lasciare spazio a un terminatore null, quindi questi caratteri vengono copiati e di terminazione null viene aggiunto; in caso contrario, strDest[0] è impostato sul carattere null e il gestore non valido di parametro viene richiamato, come descritto in Convalida dei parametri.

Esiste un'eccezione al paragrafo sopra.Se count è _TRUNCATE, quindi da parte di strSource quanto inserito in strDest viene copiato pur lascia per null di terminazione accodato sempre.

Di seguito è riportato un esempio:

char dst[5];

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

indica che ne richiede a strncpy_s per copiare length cinque caratteri in un buffer cinque byte, ciò non lascerebbe spazio per il terminatore null, gli zeri di strncpy_s alla stringa e chiama il gestore non valido di parametro.

Se il comportamento del troncamento è necessaria, utilizzare _TRUNCATE osize (– 1):

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

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

Si noti che a differenza di strncpy, se count è maggiore della lunghezza di strSource, la stringa di destinazione non viene completata con i caratteri null fino alla lunghezza count.

Il comportamento di strncpy_s non è definito se le stringhe di origine e di destinazione si sovrappongono.

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

wcsncpy_s e _mbsncpy_s sono versioni a caratteri di tipo "wide" e di caratteri multibyte di strncpy_s.Gli argomenti e il valore restituito di wcsncpy_s e mbsncpy_svariano di conseguenza.Queste ultime sei funzioni si comportano in modo identico in caso contrario.

Il valore di output è interessato dall'impostazione dell'impostazione di categoria LC_CTYPE delle impostazioni locali; vedere setlocale per ulteriori informazioni.Le versioni di queste funzioni senza il suffisso _l utilizzano le impostazioni locali correnti per il comportamento dipendente dalle impostazioni locali; le versioni con il suffisso _l sono identiche, ad eccezione del fatto che utilizzano il parametro delle impostazioni locali che viene passato.Per ulteriori informazioni, vedere Impostazioni locali.

In C++, l'utilizzo di queste funzioni è semplificato dagli overload dei modelli; gli overload possono dedurre la lunghezza del buffer automaticamente (che elimina la necessità di specificare un argomento di dimensione) e possono sostituire automaticamente le funzioni precedenti, quelle non sicure alle più recenti e le controparti sicure.Per ulteriori informazioni, vedere Assicurarsi che gli overload del modello.

La versione di debug di queste funzioni per prima cosa riempiono il buffer con il valore 0xFD.Per disabilitare questo comportamento, utilizzare _CrtSetDebugFillThreshold.

Mapping di routine a Testo generico

TCHAR.H routine

_UNICODE & _MBCS non definiti

_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]

il _strncpy_s_l, _wcsncpy_s_l e _mbsncpy_s_l non dispongono di dipendenza delle impostazioni locali e sono forniti solo per _tcsncpy_s_l e non possono essere chiamati direttamente.

Requisiti

Routine

Intestazione obbligatoria

strncpy_s, _strncpy_s_l

<string.h>

wcsncpy_s, _wcsncpy_s_l

<string.h> o <wchar.h>

_mbsncpy_s, _mbsncpy_s_l

<mbstring.h>

Per ulteriori informazioni sulla compatibilità, vedere Compatibilità nell'introduzione.

Esempio

// 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();
}
  
// 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 );

}
  

Equivalente .NET Framework

System::String::Copy

Vedere anche

Riferimenti

Modifica delle stringhe (CRT)

Impostazioni locali

Interpretazione delle 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