_snprintf_s、_snprintf_s_l、_snwprintf_s、_snwprintf_s_l_snprintf_s, _snprintf_s_l, _snwprintf_s, _snwprintf_s_l

将格式化的数据写入字符串。Writes formatted data to a string. 这些版本的 snprintf、_snprintf、_snprintf_l、_snwprintf、_snwprintf_l 具有安全增强功能,如 CRT 中的安全功能所述。These are versions of snprintf, _snprintf, _snprintf_l, _snwprintf, _snwprintf_l with security enhancements as described in Security Features in the CRT.

语法Syntax

int _snprintf_s(
   char *buffer,
   size_t sizeOfBuffer,
   size_t count,
   const char *format [,
   argument] ...
);
int _snprintf_s_l(
   char *buffer,
   size_t sizeOfBuffer,
   size_t count,
   const char *format,
   locale_t locale [,
   argument] ...
);
int _snwprintf_s(
   wchar_t *buffer,
   size_t sizeOfBuffer,
   size_t count,
   const wchar_t *format [,
   argument] ...
);
int _snwprintf_s_l(
   wchar_t *buffer,
   size_t sizeOfBuffer,
   size_t count,
   const wchar_t *format,
   locale_t locale [,
   argument] ...
);
template <size_t size>
int _snprintf_s(
   char (&buffer)[size],
   size_t count,
   const char *format [,
   argument] ...
); // C++ only
template <size_t size>
int _snwprintf_s(
   wchar_t (&buffer)[size],
   size_t count,
   const wchar_t *format [,
   argument] ...
); // C++ only

参数Parameters

bufferbuffer
输出的存储位置。Storage location for the output.

sizeOfBuffersizeOfBuffer
输出的存储位置大小。The size of the storage location for output. _Snwprintf_s_snprintf_s的大小(以字节为单位)或大小(以字节 单位)Size in bytes for _snprintf_s or size in words for _snwprintf_s.

countcount
可存储的最大字符数,或 _TRUNCATEMaximum number of characters to store, or _TRUNCATE.

formatformat
窗体控件字符串。Format-control string.

实际argument
可选参数。Optional arguments.

localelocale
要使用的区域设置。The locale to use.

返回值Return Value

_snprintf_s返回缓冲区中存储的字符数,不包括终止 null 字符。_snprintf_s returns the number of characters stored in buffer, not counting the terminating null character. _snwprintf_s返回存储在缓冲区中的宽字符数,不包括终止 null 宽字符。_snwprintf_s returns the number of wide characters stored in buffer, not counting the terminating null wide character.

如果存储数据和终止 null 值所需的存储空间超过sizeOfBuffer,则会调用无效参数处理程序,如参数验证中所述。If the storage required to store the data and a terminating null exceeds sizeOfBuffer, the invalid parameter handler is invoked, as described in Parameter Validation. 如果执行在无效的参数处理程序之后继续,则这些函数将缓冲区设置为空字符串,将Errno设置为ERANGE,并返回-1。If execution continues after the invalid parameter handler, these functions set buffer to an empty string, set errno to ERANGE, and return -1.

如果bufferformat指针,或者count小于或等于零,则调用无效的参数处理程序。If buffer or format is a NULL pointer, or if count is less than or equal to zero, the invalid parameter handler is invoked. 如果允许执行继续, 则这些函数会将errno设置为EINVAL , 并返回-1。If execution is allowed to continue, these functions set errno to EINVAL and return -1.

有关这些及其他错误代码的信息,请参阅 _doserrno、errno、_sys_errlist 和 _sys_nerrFor information about these and other error codes, see _doserrno, errno, _sys_errlist, and _sys_nerr.

备注Remarks

_Snprintf_s函数格式化并存储缓冲区中的字符或更少字符,并追加一个终止 null。The _snprintf_s function formats and stores count or fewer characters in buffer and appends a terminating null. 每个自变量(如果有)根据格式规范的相应格式规范进行转换和输出。Each argument (if any) is converted and output according to the corresponding format specification in format. 格式设置与printf系列函数一致;请参阅格式规范语法: printf 和 Wprintf 函数The formatting is consistent with the printf family of functions; see Format Specification Syntax: printf and wprintf Functions. 如果在重叠的字符串之间发生复制,则此行为不确定。If copying occurs between strings that overlap, the behavior is undefined.

如果count_TRUNCATE,则 _snprintf_s会将尽可能多的字符串写入缓冲区,同时为终止 null 留出空间。If count is _TRUNCATE, then _snprintf_s writes as much of the string as will fit in buffer while leaving room for a terminating null. 如果整个字符串(包括终止 null)都适合缓冲区,则 _snprintf_s返回写入的字符数(不包括终止 null);否则, _snprintf_s将返回-1 以指示发生了截断。If the entire string (with terminating null) fits in buffer, then _snprintf_s returns the number of characters written (not including the terminating null); otherwise, _snprintf_s returns -1 to indicate that truncation occurred.

重要

确保 format不是用户定义的字符串。Ensure that format is not a user-defined string.

_snwprintf_s_snprintf_s的宽字符版本; _snwprintf_s的指针参数是宽字符字符串。_snwprintf_s is a wide-character version of _snprintf_s; the pointer arguments to _snwprintf_s are wide-character strings. _Snwprintf_s中的编码错误检测可能与 _snprintf_s中的错误不同。Detection of encoding errors in _snwprintf_s might differ from that in _snprintf_s. _snwprintf_s(如swprintf_s)将输出写入字符串,而不是写入到类型文件的目标。_snwprintf_s, like swprintf_s, writes output to a string rather than to a destination of type FILE.

这些带有 _l后缀的函数的版本相同,只不过它们使用传入的区域设置参数而不是当前线程区域设置。The versions of these functions with the _l suffix are identical except that they use the locale parameter passed in instead of the current thread locale.

在 C++ 中,使用这些函数由模板重载简化;重载可以自动推导出缓冲区长度 (不再需要指定大小自变量),并且它们可以自动用以更新、更安全的对应物替换旧的、不安全的函数。In C++, using these functions is simplified by template overloads; the overloads can infer buffer length automatically (eliminating the need to specify a size argument) and they can automatically replace older, non-secure functions with their newer, secure counterparts. 有关详细信息,请参阅 Secure Template OverloadsFor more information, see Secure Template Overloads.

一般文本例程映射Generic-Text Routine Mappings

Tchar.h 例程Tchar.h routine 未定义 _UNICODE 和 _MBCS_UNICODE and _MBCS not defined 已定义 _MBCS_MBCS defined 已定义 _UNICODE_UNICODE defined
_sntprintf_s_sntprintf_s _snprintf_s_snprintf_s _snprintf_s_snprintf_s _snwprintf_s_snwprintf_s
_sntprintf_s_l_sntprintf_s_l _snprintf_s_l_snprintf_s_l _snprintf_s_l_snprintf_s_l _snwprintf_s_l_snwprintf_s_l

要求Requirements

例程所返回的值Routine 必需的标头Required header
_snprintf_s_snprintf_s_l_snprintf_s, _snprintf_s_l <stdio.h><stdio.h>
_snwprintf_s_snwprintf_s_l_snwprintf_s, _snwprintf_s_l <stdio.h> 或 <wchar.h><stdio.h> or <wchar.h>

有关更多兼容性信息,请参阅 兼容性For more compatibility information, see Compatibility.

示例Example

// crt_snprintf_s.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.

int snprintf_s_tester( const char * fmt, int x, size_t count )
{
   char dest[10];

   printf( "\n" );

   if ( count == _TRUNCATE )
      printf( "%zd-byte buffer; truncation semantics\n",
               _countof(dest) );
   else
      printf( "count = %zd; %zd-byte buffer\n",
               count, _countof(dest) );

   int ret = _snprintf_s( dest, _countof(dest), count, fmt, x );

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

   return ret;
}

void Examples()
{
   // formatted output string is 9 characters long: "<<<123>>>"
   snprintf_s_tester( "<<<%d>>>", 121, 8 );
   snprintf_s_tester( "<<<%d>>>", 121, 9 );
   snprintf_s_tester( "<<<%d>>>", 121, 10 );

   printf( "\nDestination buffer too small:\n" );

   snprintf_s_tester( "<<<%d>>>", 1221, 10 );

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

   int ret = snprintf_s_tester( "<<<%d>>>", 1221, _TRUNCATE );
   printf( "    truncation %s occur\n", ret == -1 ? "did"
                                                  : "did not" );

   ret = snprintf_s_tester( "<<<%d>>>", 121, _TRUNCATE );
   printf( "    truncation %s occur\n", ret == -1 ? "did"
                                                  : "did not" );
   printf( "\nSecure template overload example:\n" );

   char dest[10];
   _snprintf( dest, 10, "<<<%d>>>", 12321 );
   // With secure template overloads enabled (see #defines
   // at top of file), the preceding line is replaced by
   //    _snprintf_s( dest, _countof(dest), 10, "<<<%d>>>", 12345 );
   // Instead of causing a buffer overrun, _snprintf_s invokes
   // the invalid parameter handler.
   // If secure template overloads were disabled, _snprintf would
   // write 10 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();
}

count = 8; 10-byte buffer
    new contents of dest: '<<<121>>'

count = 9; 10-byte buffer
    new contents of dest: '<<<121>>>'

count = 10; 10-byte buffer
    new contents of dest: '<<<121>>>'

Destination buffer too small:

count = 10; 10-byte buffer
Invalid parameter handler invoked: ("Buffer too small", 0)
    new contents of dest: ''

Truncation examples:

10-byte buffer; truncation semantics
    new contents of dest: '<<<1221>>'
    truncation did occur

10-byte buffer; truncation semantics
    new contents of dest: '<<<121>>>'
    truncation did not occur

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

请参阅See also

流 I/OStream I/O
sprintf、_sprintf_l、swprintf、_swprintf_l、__swprintf_lsprintf, _sprintf_l, swprintf, _swprintf_l, __swprintf_l
fprintf、_fprintf_l、fwprintf、_fwprintf_lfprintf, _fprintf_l, fwprintf, _fwprintf_l
printf、_printf_l、wprintf、_wprintf_lprintf, _printf_l, wprintf, _wprintf_l
scanf、_scanf_l、wscanf、_wscanf_lscanf, _scanf_l, wscanf, _wscanf_l
sscanf、_sscanf_l、swscanf、_swscanf_lsscanf, _sscanf_l, swscanf, _swscanf_l
vprintf 函数vprintf Functions