home *** CD-ROM | disk | FTP | other *** search
/ NetNews Usenet Archive 1992 #19 / NN_1992_19.iso / spool / comp / lang / c / 12981 < prev    next >
Encoding:
Internet Message Format  |  1992-08-30  |  2.2 KB

  1. Path: sparky!uunet!mcsun!news.funet.fi!hydra!klaava!wirzeniu
  2. From: wirzeniu@klaava.Helsinki.FI (Lars Wirzenius)
  3. Newsgroups: comp.lang.c
  4. Subject: Re: Novice Questions
  5. Message-ID: <1992Aug30.101121.4479@klaava.Helsinki.FI>
  6. Date: 30 Aug 92 10:11:21 GMT
  7. References: <1992Aug30.004740.8973@eskimo.celestial.com>
  8. Organization: University of Helsinki
  9. Lines: 57
  10.  
  11. maven@eskimo.celestial.com (Norman Hamer) writes:
  12. > 1. Given a char array, say char foo[256];, is *foo the same as foo[0]
  13. >and is foo+x the same as foo[x] in all implementations?
  14.  
  15. *foo and foo[0] are identical, and *(foo+x) and foo[x] are identical. 
  16. The latter is by definition: the language is defined that way.  The
  17. former follows directly from the latter: foo[0] <=> *(foo+0) <=> *(foo)
  18. <=> *foo.
  19.  
  20. > 2. What's the best way to read in a text configuration file? I've seen
  21. >code like this:
  22.  
  23. > fgets(line, 80, fd);
  24. > while(!feof(fd))
  25. > {
  26. >   /* Muck with the data */
  27. >   fgets(line, 80, fd);
  28. > }
  29.  
  30. Works, but is ugly, since it duplicates the read statement, and makes it
  31. easy to miss one of them when changing the other one.  Doesn't check for
  32. ferror.
  33.  
  34. > while(fgets(line, 80, fd) != NULL)
  35. > {
  36. >   /*Muck with the data */
  37. > }
  38.  
  39. Preferred, and the way that practically everybody does it.  An idiom in
  40. C.  Concentrates all the line reading logic into one place and has only
  41. the data mucking inside the loop, and nothing else there, so the data
  42. mucking is nicely isolated.
  43.  
  44. > while(!feof(fd))
  45. > {
  46. >    fgets(line, 80, fd);
  47. >    if(feof(fd))
  48. >        break;
  49. >    /* Muck with the data */
  50. > }
  51.  
  52. Even uglier than the first one, although more similar to Pascal (that is
  53. not a virtue, although not necessarily a bad thing either).  Includes an
  54. unnecessary goto (spelled break here), which confuses the logic of the
  55. loop.  Also, this doesn't check for errors, you'd need to check for
  56. ferror as well, but then it gets uglier and uglier.
  57.  
  58. > Which one is best and why?  Which is the least likely to provide
  59. >erroneous results (the last one if you forget the second feof() will
  60. >sometimes leave you with a portion of the last line... not all of it and
  61. >not a null string)
  62.  
  63. The second one is best, 'cause it's the simplest and most common way of
  64. doing it, and the most difficult to get wrong.
  65.  
  66. --
  67. Lars.Wirzenius@helsinki.fi
  68.