home *** CD-ROM | disk | FTP | other *** search
- Newsgroups: comp.lang.c
- Path: sparky!uunet!snorkelwacker.mit.edu!bloom-picayune.mit.edu!news
- From: scs@adam.mit.edu (Steve Summit)
- Subject: Re: sscanf and portability
- Message-ID: <1992Sep15.005935.19233@athena.mit.edu>
- Sender: news@athena.mit.edu (News system)
- Nntp-Posting-Host: adam.mit.edu
- Organization: none, at the moment
- References: <RUJO.92Sep14160231@ulrik.uio.no>
- Date: Tue, 15 Sep 1992 00:59:35 GMT
- Lines: 47
-
- In article <RUJO.92Sep14160231@ulrik.uio.no>, rujo@ulrik.uio.no (Rune J|rgensen) writes:
- > If you use types that explisit defines a byte size, e.g.:
- >
- > typedef short INT16;
- > typedef long INT32;
- > INT16 i16;
- > INT32 i32;
- >
- > How do you preserve portability with sscanf? E.g:
-
- Mit Schwierigkeit, as they say in Deutschland.
-
- Defining types with precise numbers of bits is a bit of a
- perversion on the intent of C's type system, so it is not too
- surprising that occasional difficulties like this arise. When
- precisely-sized types are truly necessary, typedefs like the
- above are the right way to implement them, but their necessity
- should be rare. (I don't believe I have ever used such a type.)
-
- The traditional need for precisely-sized types arises of course
- when people fall into the trap of using "binary" data files or
- otherwise attempting to conform to externally-imposed storage
- layouts. Such situations should themselves be much rarer than
- they are, further minimizing the occurrence of the problem which
- Rune mentions. Nevertheless, if a program does use precisely-sized
- variables to facilitate "binary" I/O, it should have fewer places
- where it needs to perform text I/O (scanf/printf) using those
- variables.
-
- Obviously, some of the numbers which are read from or written to
- a data file must be respectively presented to or requested from
- the user, but scanf is a notoriously poor vehicle for interactive
- input and should itself be avoided, and printf uses values rather
- than pointers such that conservative format-specifiers and
- explicit casts solve the problem rather easily:
-
- printf("%d %ld", (int)i16, (long)i32);
-
- If I were faced with this problem, I'd ask myself carefully
- whether I really needed to be using precisely-sized types at all,
- and whether I really needed to use scanf. If both were in fact
- absolutely necessary, the solution (using temporary variables and
- extra assignments) which Lars Wirzenius has already outlined
- would be about the best that could be done.
-
- Steve Summit
- scs@adam.mit.edu
-