Previous: Printf Extension Example, Up: Customizing Printf

#### 12.13.5 Predefined `printf` Handlers

The GNU C Library also contains a concrete and useful application of the `printf` handler extension. There are two functions available which implement a special way to print floating-point numbers.

— Function: int printf_size (FILE *fp, const struct printf_info *info, const void *const *args)

> Print a given floating point number as for the format `%f` except that there is a postfix character indicating the divisor for the number to make this less than 1000. There are two possible divisors: powers of 1024 or powers of 1000. Which one is used depends on the format character specified while registered this handler. If the character is of lower case, 1024 is used. For upper case characters, 1000 is used.

> The postfix tag corresponds to bytes, kilobytes, megabytes, gigabytes, etc. The full table is:

> The default precision is 3, i.e., 1024 is printed with a lower-case format character as if it were `%.3fk` and will yield `1.000k`.

Due to the requirements of `register_printf_function` we must also provide the function which returns information about the arguments.

— Function: int printf_size_info (const struct printf_info *info, size_t n, int *argtypes)

> This function will return in argtypes the information about the used parameters in the way the `vfprintf` implementation expects it. The format always takes one argument.

To use these functions both functions must be registered with a call like

         register_printf_function ('B', printf_size, printf_size_info);

Here we register the functions to print numbers as powers of 1000 since the format character `'B'` is an upper-case character. If we would additionally use `'b'` in a line like

         register_printf_function ('b', printf_size, printf_size_info);

we could also print using a power of 1024. Please note that all that is different in these two lines is the format specifier. The `printf_size` function knows about the difference between lower and upper case format specifiers.

The use of `'B'` and `'b'` is no coincidence. Rather it is the preferred way to use this functionality since it is available on some other systems which also use format specifiers.