NetBSD-Users archive
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index][Old Index]
Re: C portability question
On Sun, 11 May 2008 20:35:39 -0400
"Greg A. Woods; Planix, Inc." <woods%planix.ca@localhost> wrote:
>
> On 11-May-08, at 7:49 PM, Steven M. Bellovin wrote:
>
> > Working on a package, I had problems with (in effect)
> >
> > off_t var;
> > printf("%ld\n", var);
> >
> > This crashes on netbsd-i386, since our longs are 4 bytes. (I didn't
> > quite see what off_t is, but it's 8 bytes long.)
> >
> > Anyway -- what is the portable way to printf an off_t, which is (of
> > course) an opaque type. I could cast (var) to (long), but that's
> > clearly wrong (and in fact loses data here for us).
>
> C99 defines printf (and scanf) format specifiers for various integer
> types (which you'll find actually defined in <machine/int_fmtio.h>
> on NetBSD since 1.6):
>
> #include <sys/types.h> /* for off_t */
> #include <inttypes.h>
> #include <limits.h>
> #include <stdint.h>
> #include <stdio.h>
>
> off_t var = INT64_MAX;
>
> /* assert(sizeof(off_t) <= sizeof(int64_t)); */
>
> printf("%" PRId64 "\n", (int64_t) var);
>
> Without C99 though (on at least I32/LP32 architectures) you may be
> stuck with trying to figure out if the compiler supports "long long"
> or similar and what printf() offers for printing "long long" (eg.
> "%q", assuming of course sizeof(off_t) is also actually greater than
> 4 on the target platform.
>
Thanks, that helps -- but what is the format specifier for off_t?
After all, I don't know what type it is. I see your assert(), but that
strikes me as ugly. I could, I guess, just cast to int64_t, since in
this context anything larger is highly unlikely (it's the size of a
mail message, and I don't think people are receiving >2^64 bytes of
mail in one message...)
--Steve Bellovin, http://www.cs.columbia.edu/~smb
Home |
Main Index |
Thread Index |
Old Index