pkgsrc-Users archive

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index][Old Index]

Re: C portability question

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.

                                        Greg A. Woods; Planix, Inc.

Home | Main Index | Thread Index | Old Index