How to use printf to display off_t, nlink_t, size_t and other special types?

There isn’t a fully portable way to do it, and it is a nuisance.

C99 provides a mechanism for built-in types like size_t with the %zu notation (and there are some extra, similar qualifiers).

It also provides the <inttypes.h> header with macros such as PRIX32 to define the correct qualifier for printing a 32-bit hexadecimal constant (in this case):

printf("32-bit integer: 0x%08" PRIX32 "\n", var_of_type_int32_t);

For the system-defined types (such as those defined by POSIX), AFAIK, there is no good way to handle them. So, what I do is take a flying guess at a ‘safe’ conversion and then print accordingly, including the cast, which is what you illustrate in the question. It is frustrating, but there is no better way that I know of. In case of doubt, and using C99, then conversion to ‘unsigned long long’ is pretty good; there could be a case for using a cast to uintmax_t and PRIXMAX or equivalent.

Or, as FUZxxl reminded me, you can use the modifier j to indicate a ‘max’ integer type. For example:

printf("Maximal integer: 0x%08jX\n", (uintmax_t)var_of_type_without_format_letter);

Leave a Comment