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

前端 未结 1 838
眼角桃花
眼角桃花 2020-11-29 07:19

In my program, I stat the files they want and send the data over. The fields of a stat struct are all special types:

struct stat {
  dev_t     s         


        
相关标签:
1条回答
  • 2020-11-29 08:00

    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);
    
    0 讨论(0)
提交回复
热议问题