home *** CD-ROM | disk | FTP | other *** search
- Path: sparky!uunet!mcsun!news.funet.fi!hydra!klaava!wirzeniu
- From: wirzeniu@klaava.Helsinki.FI (Lars Wirzenius)
- Newsgroups: comp.lang.c
- Subject: Re: Novice Questions
- Message-ID: <1992Aug30.101121.4479@klaava.Helsinki.FI>
- Date: 30 Aug 92 10:11:21 GMT
- References: <1992Aug30.004740.8973@eskimo.celestial.com>
- Organization: University of Helsinki
- Lines: 57
-
- maven@eskimo.celestial.com (Norman Hamer) writes:
- > 1. Given a char array, say char foo[256];, is *foo the same as foo[0]
- >and is foo+x the same as foo[x] in all implementations?
-
- *foo and foo[0] are identical, and *(foo+x) and foo[x] are identical.
- The latter is by definition: the language is defined that way. The
- former follows directly from the latter: foo[0] <=> *(foo+0) <=> *(foo)
- <=> *foo.
-
- > 2. What's the best way to read in a text configuration file? I've seen
- >code like this:
-
- > fgets(line, 80, fd);
- > while(!feof(fd))
- > {
- > /* Muck with the data */
- > fgets(line, 80, fd);
- > }
-
- Works, but is ugly, since it duplicates the read statement, and makes it
- easy to miss one of them when changing the other one. Doesn't check for
- ferror.
-
- > while(fgets(line, 80, fd) != NULL)
- > {
- > /*Muck with the data */
- > }
-
- Preferred, and the way that practically everybody does it. An idiom in
- C. Concentrates all the line reading logic into one place and has only
- the data mucking inside the loop, and nothing else there, so the data
- mucking is nicely isolated.
-
- > while(!feof(fd))
- > {
- > fgets(line, 80, fd);
- > if(feof(fd))
- > break;
- > /* Muck with the data */
- > }
-
- Even uglier than the first one, although more similar to Pascal (that is
- not a virtue, although not necessarily a bad thing either). Includes an
- unnecessary goto (spelled break here), which confuses the logic of the
- loop. Also, this doesn't check for errors, you'd need to check for
- ferror as well, but then it gets uglier and uglier.
-
- > Which one is best and why? Which is the least likely to provide
- >erroneous results (the last one if you forget the second feof() will
- >sometimes leave you with a portion of the last line... not all of it and
- >not a null string)
-
- The second one is best, 'cause it's the simplest and most common way of
- doing it, and the most difficult to get wrong.
-
- --
- Lars.Wirzenius@helsinki.fi
-