How should I print types like off_t and size_t?
For Microsoft, the answer is different. VS2013 is largely C99 compliant but "[t]he hh, j, z, and t length prefixes are not supported." For size_t "that is, unsigned __int32 on 32-bit platforms, unsigned __int64 on 64-bit platforms" use prefix I (capital eye) with type specifier o, u, x, or X. See VS2013 Size specification
As for off_t, it is defined as long in VC\include\sys\types.h.
To print off_t
:
printf("%jd\n", (intmax_t)x);
To print size_t
:
printf("%zu\n", x);
To print ssize_t
:
printf("%zd\n", x);
See 7.19.6.1/7 in the C99 standard, or the more convenient POSIX documentation of formatting codes:
http://pubs.opengroup.org/onlinepubs/009695399/functions/fprintf.html
If your implementation doesn't support those formatting codes (for example because you're on C89), then you have a bit of a problem since AFAIK there aren't integer types in C89 that have formatting codes and are guaranteed to be as big as these types. So you need to do something implementation-specific.
For example if your compiler has long long
and your standard library supports %lld
, you can confidently expect that will serve in place of intmax_t
. But if it doesn't, you'll have to fall back to long
, which would fail on some other implementations because it's too small.
Which version of C are you using?
In C90, the standard practice is to cast to signed or unsigned long, as appropriate, and print accordingly. I've seen %z for size_t, but Harbison and Steele don't mention it under printf(), and in any case that wouldn't help you with ptrdiff_t or whatever.
In C99, the various _t types come with their own printf macros, so something like "Size is " FOO " bytes."
I don't know details, but that's part of a fairly large numeric format include file.
You can use z
for size_t and t
for ptrdiff_t like in
printf("%zu %td", size, ptrdiff);
But my manpage says some older library used a different character than z
and discourages use of it. Nevertheless, it's standardized (by the C99 standard). For those intmax_t
and int8_t
of stdint.h
and so on, there are macros you can use, like another answer said:
printf("value: %" PRId32, some_int32_t);
printf("value: %" PRIu16, some_uint16_t);
They are listed in the manpage of inttypes.h
.
Personally, I would just cast the values to unsigned long
or long
like another answer recommends. If you use C99, then you can (and should, of course) cast to unsigned long long
or long long
and use the %llu
or %lld
formats respectively.