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

半城伤御伤魂 提交于 2019-11-27 01:41:21
Jonathan Leffler

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);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!