core/doc/snprintf.qbk
Andrey Semashev be8790115c Added portable snprintf/vsnprintf definition.
This definitions is mostly a workaround for older MSVC versions that only
provided non-portable _snprintf etc. that are not fully conforming to
the standard snprintf. This implementation fixes its issues wrt. null
termination and returned values in case of buffer overflows.

On platforms that support the standard snprintf, the definitions in
the header are equivalent to the standard functions.
2022-12-09 03:53:01 +03:00

48 lines
1.9 KiB
Plaintext

[/
/ Copyright (c) 2022 Andrey Semashev
/
/ Distributed under the Boost Software License, Version 1.0. (See accompanying
/ file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
/]
[section:snprintf snprintf]
[simplesect Authors]
* Andrey Semashev
[endsimplesect]
[section Header <boost/core/snprintf.hpp>]
The header `<boost/core/snprintf.hpp>` provides portable definition of [@https://en.cppreference.com/w/c/io/fprintf `snprintf`],
`vsnprintf` and their corresponding `wchar_t` counterparts. On a platform that supports these functions in the standard library,
these definitions are equivalent to the standard functions. On other platforms (mainly, older MSVC versions) these functions
are emulated through non-standard functions that have similar behavior.
Depending on the standard library, certain implementation differences are exposed to the user:
* Any non-standard behavior with respect to string format description are not hidden by the emulation.
* Returned value of `boost::core::snprintf` in case if the output buffer is too small may not be equal to the number of characters
that would have been written if the buffer was large enough. It is, however, equal or larger than the buffer size,
which still allows the caller to detect the buffer overflow condition. The formatted output is still properly null-terminated
in this case.
[note Unlike `snprintf`, `swprintf` does not return the number of characters to be written if the output buffer is too small
but returns -1 instead. Furthermore, `swprintf` may or may not produce characters in the output buffer in this case.]
[section Example]
``
char buf[10];
int n = boost::core::snprintf(buf, sizeof(buf), "%d", i);
if (n < 0)
throw std::runtime_error("Formatting error");
if (n >= sizeof(buf))
throw std::runtime_error("Formatting buffer overflow");
``
[endsect]
[endsect]
[endsect]