sexta-feira, 16 de janeiro de 2009

printf format specifications quick reference

The printf man page is more like a specification than a quick reference.
Here is my quick reference for the "conversion specifications format"
aka the "format specification fields". Note this info is based on
the printf man page in man-pages-1.67-7 from the LDP (on Fedora Core 4)
%[flags][min field width][precision][length]conversion specifier
----- --------------- --------- ------ -------------------
\ #,*
.#, .* / \
\ / \
#,0,-,+, ,',I hh,h,l,ll,j,z,L c,d,u,x,X,e,f,g,s,p,%
------------- --------------- -----------------------
# | Alternate, hh | char, c | unsigned char,
0 | zero pad, h | short, d | signed int,
- | left align, l | long, u | unsigned int,
+ | explicit + - sign, ll | long long, x | unsigned hex int,
| space for + sign, j | [u]intmax_t, X | unsigned HEX int,
' | locale thousands grouping, z | size_t, e | [-]d.ddde±dd double,
I | Use locale's alt digits t | ptrdiff_t, E | [-]d.dddE±dd double,
L | long double,
---------=====
if no precision => 6 decimal places / f | [-]d.ddd double,
if precision = 0 => 0 decimal places _____/ g | e|f as appropriate,
if precision = # => # decimal places G | E|F as appropriate,
if flag = # => always show decimal point s | string,
..............------
/ p | pointer,
if precision => max field width / % | %

Examples of common combinations:
formatoutput
printf("%08X",32_bit_var);0000ABCD
printf("%lu",32_bit_var);43981
printf("%'d",32_bit_var);43,981
printf("%10s","string"); string
printf("%*s",10,"string"); string
printf("%-10s","string");string
printf("%-10.10s","truncateiftoolong");truncateif

Note for the %'d one to work you must have already set your locale as in the following example:
#include 
#include

int main(void)
{
setlocale(LC_ALL,"");
printf("%'Id\n",1234);
}
$ ./numtest
1,234

$ LANG=fa_IR.utf8 ./numtest
۱٬۲۳۴
For details on printing system types like off_t, and time_t and the C99 types like uint32_t etc. portably, please see here.

Nenhum comentário: