StringCchPrintf Function
StringCchPrintf is a replacement for sprintf. It accepts a format string and a list of arguments and returns a formatted string. The size, in characters, of the destination buffer is provided to the function to ensure thatStringCchPrintf does not write past the end of this buffer.
Syntax
HRESULT StringCchPrintf( LPTSTR pszDest, size_t cchDest, LPCTSTR pszFormat, ... );
Parameters
pszDest
- [out] Pointer to a buffer which receives the formatted, null-terminated string created from pszFormat and its arguments.
cchDest- [in] Size of the destination buffer, in characters. This value must be sufficiently large to accommodate the final formatted string plus 1 to account for the terminating null character. The maximum number of characters allowed is STRSAFE_MAX_CCH.
pszFormat- [in] Pointer to a buffer containing a printf-style format string. This string must be null-terminated.
...- [in] Arguments to be inserted into pszFormat.
Return Value
Note that this function returns an HRESULT as opposed to sprintf, which returns the number of bytes stored in its destination buffer. It is strongly recommended that you use the SUCCEEDED and FAILED macros to test the return value of this function.
S_OK There was sufficient space for the result to be copied to pszDest without truncation, and the buffer is null-terminated. STRSAFE_E_INVALID_PARAMETER The value in cchDest is either 0 or larger than STRSAFE_MAX_CCH. STRSAFE_E_INSUFFICIENT_BUFFER The copy operation failed due to insufficient buffer space. The destination buffer contains a truncated, null-terminated version of the intended result. In situations where truncation is acceptable, this may not necessarily be seen as a failure condition.
Remarks
StringCchPrintf provides additional processing for proper buffer handling in your code. Poor buffer handling is implicated in many security issues that involve buffer overruns.StringCchPrintf always null-terminates a non-zero-length destination buffer.
StringCchPrintf can be used in its generic form, or specifically asStringCchPrintfA (for ANSI strings) or StringCchPrintfW (for Unicode strings). The form to use is determined by your data.
String Data Type String Literal Function char "string" StringCchPrintfA TCHAR TEXT("string") StringCchPrintf WCHAR L"string" StringCchPrintfW StringCchPrintf and its ANSI and Unicode variants are replacements for these functions:
Behavior is undefined if the strings pointed to by pszDest, pszFormat, or any argument strings overlap.
Neither pszFormat nor pszDest should be NULL. See StringCchPrintfEx if you require the handling of null string pointer values.
Example
The following example shows a simple use of StringCchPrintf, using four arguments.
TCHAR pszDest[30]; size_t cchDest = 30; LPCTSTR pszFormat = TEXT("%s %d + %d = %d."); TCHAR* pszTxt = TEXT("The answer is"); HRESULT hr = StringCchPrintf(pszDest, cchDest, pszFormat, pszTxt, 1, 2, 3); // The resultant string at pszDest is "The answer is 1 + 2 = 3."