snprintf.c
- yet another portable implementation of snprintf

snprintf is a routine to convert numeric and string arguments to formatted strings. It is similar to sprintf(3) provided in a system's C library, yet it requires an additional argument - the buffer size - and it guarantees never to store anything beyond the given buffer, regardless of the format or arguments to be formatted. Some newer operating systems do provide snprintf in their C library, but many do not or do provide an inadequate (slow or idiosyncratic) version, which calls for a portable implementation of this routine.

Author

Mark Martinec <mark.martinec@ijs.si>, April 1999
Copyright ©: Mark Martinec

Terms and conditions ...

... for copying, distribution and modification, NO WARRANTY:
GNU GENERAL PUBLIC LICENSE, Version 2 or later

Features

Supported formats and data types

This snprintf only supports format specifiers: s, c, d, o, u, x, X, p (and synonyms: i, D, U, O - see below) with flags: '-', '+', ' ', '0' and '#'. An asterisk is supported for field width as well as precision.

Data type modifiers 'h' (short int), 'l' (long int) and 'll' (long long int) are supported.

NOTE:

If macro SNPRINTF_LONGLONG_SUPPORT is not defined (default) the data type modifier 'll' is recognized but treated the same as 'l', which may cause argument value truncation! Defining SNPRINTF_LONGLONG_SUPPORT requires that your system's sprintf also handles data type modifier 'll'. long long int is a language extension which may not be portable.

Conversion of numeric data (formats d, o, u, x, X, p) with data type modifiers (none or h, l, ll) is left to the system routine sprintf, but all handling of flags, field width and precision as well as c and s formats is done very carefully by this portable routine. If a string precision (truncation) is specified (e.g. %.8s) it is guaranteed the string beyond the specified precision will not be referenced.

Data type modifiers h, l and ll are ignored for c and s formats (data types wint_t and wchar_t are not supported).

The following common synonyms for conversion characters are supported:

The following is specifically not supported:

Availability

http://www.ijs.si/software/snprintf/

Other implementations of snprintf

I am aware of some other portable implementations of snprintf. I do not claim they are public - please refer to their respective copyright and licensing terms. If you know of other versions please let me know. In retrospect, it appears that a lot of effort was wasted by many people for not being aware of what others are doing. Sigh.


mm