snprintf、_snprintf、_snprintf_l、_snwprintf、_snwprintf_lsnprintf, _snprintf, _snprintf_l, _snwprintf, _snwprintf_l

将格式化的数据写入字符串。Writes formatted data to a string. 提供这些函数的更多安全版本,请参阅 _snprintf_s、_snprintf_s_l、_snwprintf_s、_snwprintf_s_lMore secure versions of these functions are available; see _snprintf_s, _snprintf_s_l, _snwprintf_s, _snwprintf_s_l.

语法Syntax

int snprintf(  
   char *buffer,  
   size_t count,  
   const char *format [,  
   argument] ...   
);  
int _snprintf(  
   char *buffer,  
   size_t count,  
   const char *format [,  
   argument] ...   
);  
int _snprintf_l(  
   char *buffer,  
   size_t count,  
   const char *format,  
   locale_t locale [,  
   argument] ...   
);  
int _snwprintf(  
   wchar_t *buffer,  
   size_t count,  
   const wchar_t *format [,  
   argument] ...   
);  
int _snwprintf_l(  
   wchar_t *buffer,  
   size_t count,  
   const wchar_t *format,  
   locale_t locale [,  
   argument] ...   
);  
template <size_t size>  
int _snprintf(  
   char (&buffer)[size],  
   size_t count,  
   const char *format [,  
   argument] ...   
); // C++ only  
template <size_t size>  
int _snprintf_l(  
   char (&buffer)[size],  
   size_t count,  
   const char *format,  
   locale_t locale [,  
   argument] ...   
); // C++ only  
template <size_t size>  
int _snwprintf(  
   wchar_t (&buffer)[size],  
   size_t count,  
   const wchar_t *format [,  
   argument] ...   
); // C++ only  
template <size_t size>  
int _snwprintf_l(  
   wchar_t (&buffer)[size],  
   size_t count,  
   const wchar_t *format,  
   locale_t locale [,  
   argument] ...   
); // C++ only  

参数Parameters

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

count
可存储的最多字符数。Maximum number of characters to store.

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

argument
可选参数。Optional arguments.

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

有关详细信息,请参阅格式规范语法:printf 和 wprintf 函数For more information, see Format Specification Syntax: printf and wprintf Functions.

返回值Return Value

len 设为格式化数据字符串的长度,不包括终止 null。Let len be the length of the formatted data string, not including the terminating null. 对于 lencountsnprintf_snprintf以字节为单位,而对于 _snwprintf则以宽字符为单位。Both len and count are in bytes for snprintf and _snprintf, wide characters for _snwprintf.

对于所有函数,如果 len < countlen 个字符将存储在 buffer中,附加 null 终止符,并返回 lenFor all functions, if len < count, len characters are stored in buffer, a null-terminator is appended, and len is returned.

snprintf 大于或等于 len 时, count函数将通过在 buffer[count-1]放置 null 终止符以截断输出。The snprintf function truncates the output when len is greater than or equal to count, by placing a null-terminator at buffer[count-1]. 返回的值为 len,即当 count 足够大时将输出的字符数。The value returned is len, the number of characters that would have been output if count was large enough. 当发生编码错误时, snprintf 函数返回一个负值。The snprintf function returns a negative value if an encoding error occurs.

对于除 snprintf外的所有函数,如果 len = countlen 个字符将存储在 buffer中,不附加任何 null 终止符,并且返回 lenFor all functions other than snprintf, if len = count, len characters are stored in buffer, no null-terminator is appended, and len is returned. 如果 len > countcount 个字符将存储在 buffer中,不附加 null 终止符,并返回负值。If len > count, count characters are stored in buffer, no null-terminator is appended, and a negative value is returned.

如果 buffer 为 null 指针,并且 count 为零, len 将返回为设置输出格式所需的字符数,不包括终止 null。If buffer is a null pointer and count is zero, len is returned as the count of characters required to format the output, not including the terminating null. 若要使用相同的 argumentlocale 参数进行成功调用,请分配至少容纳 len + 1 个字符的缓冲区。To make a successful call with the same argument and locale parameters, allocate a buffer holding at least len + 1 characters.

如果 buffer 为 null 指针,并且 count 不为零,或者如果 format 为 null 指针,则调用无效参数处理程序,如 Parameter ValidationIf buffer is a null pointer and count is nonzero, or if format is a null pointer, the invalid parameter handler is invoked, as described in Parameter Validation. 如果允许继续执行,则这些函数返回 -1 并将 errno 设置为 EINVALIf execution is allowed to continue, these functions return -1 and set errno to EINVAL.

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

备注Remarks

snprintf 函数和 _snprintf 系列函数在 count 中格式化和存储 buffer或更少字符。The snprintf function and the _snprintf family of functions format and store count or fewer characters in buffer. snprintf 函数始终存储终止 null 字符,并在必要时截断输出。The snprintf function always stores a terminating null character, truncating the output if necessary. 仅当格式化字符串的长度严格小于 _snprintf 个字符时, count 系列函数才附加终止 null 字符。The _snprintf family of functions only appends a terminating null character if the formatted string length is strictly less than count characters. 每个 argument (如果有)根据 format中相应的格式规范进行转换和输出。Each argument (if any) is converted and is output according to the corresponding format specification in format. 该格式包括普通字符,其形式和函数与 format printf 参数相同。The format consists of ordinary characters and has the same form and function as the format argument for printf. 如果在重叠的字符串之间发生复制,则此行为不确定。If copying occurs between strings that overlap, the behavior is undefined.

重要

确保 format 不是用户定义的字符串。Ensure that format is not a user-defined string. 由于 _snprintf 函数不保证 null 终止,特别是返回值为 count时,因此请确保在其后追加用于添加 null 终止符的代码。Because the _snprintf functions do not guarantee NULL termination—in particular, when the return value is count—make sure that they are followed by code that adds the null terminator. 有关详细信息,请参阅 避免缓冲区溢出For more information, see Avoiding Buffer Overruns.

从 Visual Studio 2015 和 Windows 10 中的 UCRT 开始, snprintf 不再等于 _snprintfBeginning with the UCRT in Visual Studio 2015 and Windows 10, snprintf is no longer identical to _snprintf. snprintf 函数行为现在符合 C99 标准。The snprintf function behavior is now C99 standard compliant.

_snwprintf_snprintf的宽字符版本;_snwprintf 的指针参数是宽字符串。_snwprintf is a wide-character version of _snprintf; the pointer arguments to _snwprintf are wide-character strings. _snwprintf 中对编码错误的检测可能与 _snprintf 中不同。Detection of encoding errors in _snwprintf might differ from that in _snprintf. _snwprintf 就像 swprintf,将输出写入字符串,而非 FILE 类型的目标。_snwprintf, just like swprintf, writes output to a string instead of a destination of type FILE.

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

在 C++ 中,这些函数具有模板重载,可调用更新、更安全的版本。In C++, these functions have template overloads that invoke their newer, more 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 _snprintf _snprintf _snwprintf
_sntprintf_l _snprintf_l _snprintf_l _snwprintf_l

要求Requirements

例程Routine 必需的标头Required header
snprintf, _snprintf, _snprintf_lsnprintf, _snprintf, _snprintf_l <stdio.h><stdio.h>
_snwprintf, _snwprintf_l_snwprintf, _snwprintf_l <stdio.h> 或 <wchar.h><stdio.h> or <wchar.h>

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

示例Example

// crt_snprintf.c  
// compile with: /W3  
#include <stdio.h>  
#include <stdlib.h>  

#if !defined(__cplusplus)  
typedef int bool;  
const bool true = 1;  
const bool false = 0;  
#endif  

#define FAIL 0 // change to 1 and see what happens  

int main(void)  
{  
   char buffer[200];  
   const static char s[] = "computer"  
#if FAIL  
"computercomputercomputercomputercomputercomputercomputercomputer"  
"computercomputercomputercomputercomputercomputercomputercomputer"  
"computercomputercomputercomputercomputercomputercomputercomputer"  
"computercomputercomputercomputercomputercomputercomputercomputer"  
#endif  
   ;  
   const char c = 'l';   
   const int i = 35;  
#if FAIL  
   const double fp = 1e300; // doesn't fit in the buffer  
#else  
   const double fp = 1.7320534;  
#endif  
   /* !subtract one to prevent "squeezing out" the terminal nul! */  
   const int bufferSize = sizeof(buffer)/sizeof(buffer[0]) - 1;  
   int bufferUsed = 0;  
   int bufferLeft = bufferSize - bufferUsed;  
   bool bSuccess = true;  
   buffer[0] = 0;  

   /* Format and print various data: */  

   if (bufferLeft > 0)  
   {  
      int perElementBufferUsed = _snprintf(&buffer[bufferUsed],   
      bufferLeft, "   String: %s\n", s ); // C4996  
      // Note: _snprintf is deprecated; consider _snprintf_s instead  
      if (bSuccess = (perElementBufferUsed >= 0))  
      {  
         bufferUsed += perElementBufferUsed;  
         bufferLeft -= perElementBufferUsed;  
         if (bufferLeft > 0)  
         {  
            int perElementBufferUsed = _snprintf(&buffer[bufferUsed],   
            bufferLeft, "   Character: %c\n", c ); // C4996  
            if (bSuccess = (perElementBufferUsed >= 0))  
            {  
               bufferUsed += perElementBufferUsed;  
               bufferLeft -= perElementBufferUsed;  
               if (bufferLeft > 0)  
               {  
                  int perElementBufferUsed = _snprintf(&buffer  
                  [bufferUsed], bufferLeft, "   Integer: %d\n", i ); // C4996  
                  if (bSuccess = (perElementBufferUsed >= 0))  
                  {  
                     bufferUsed += perElementBufferUsed;  
                     bufferLeft -= perElementBufferUsed;  
                     if (bufferLeft > 0)  
                     {  
                        int perElementBufferUsed = _snprintf(&buffer  
                        [bufferUsed], bufferLeft, "   Real: %f\n", fp ); // C4996  
                        if (bSuccess = (perElementBufferUsed >= 0))  
                        {  
                           bufferUsed += perElementBufferUsed;  
                        }  
                     }  
                  }  
               }  
            }  
         }  
      }  
   }  

   if (!bSuccess)  
   {  
      printf("%s\n", "failure");  
   }  
   else  
   {  
      /* !store nul because _snprintf doesn't necessarily (if the string   
       * fits without the terminal nul, but not with it)!  
       * bufferUsed might be as large as bufferSize, which normally is   
       * like going one element beyond a buffer, but in this case   
       * subtracted one from bufferSize, so we're ok.  
       */  
      buffer[bufferUsed] = 0;  
      printf( "Output:\n%s\ncharacter count = %d\n", buffer, bufferUsed );  
   }  
   return EXIT_SUCCESS;  
}  
Output:  
   String: computer  
   Character: l  
   Integer: 35  
   Real: 1.732053  

character count = 69  

另请参阅See Also

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