[prog] C problem I am unable to solve

Almut Behrens almut-behrens at gmx.net
Fri May 13 03:39:53 EST 2005


On Thu, May 12, 2005 at 04:11:10PM +0100, Dan wrote:
> On Thu, May 12, 2005 at 10:48:03AM -0400, Angelina Carlton wrote:
> > The problem I have now is an infinate loop once it reaches the end of
> > the file.
> 
> I think the problem is here:
> 
> >      while ( (c = getc(inputfile)) != '\n' )
> >         putc(c, stdout); /* display the line */
> 
> EOF is not '\n'     :-)

Exactly...  Also, there's another subtle problem you might not yet have
noticed: the character you read in your outer while-loop

> >   while ( ((c = getc(inputfile)) != EOF)) {

will be silently dropped from the output...

Of course, you could always add code to work around these issues, but
generally, it's a good idea to keep things as simple as posible.
Programs grow into little monsters all by themselves... ;)

In that spirit, I'd suggest you do something like this:

int read_file(FILE *inputfile) {
  int c, q, linenr=0;
  
  while ( (c = getc(inputfile)) != EOF ) {
    putc(c, stdout);          /* copy char to stdout */
    if (c == '\n') linenr++;  /* count lines */
    if (linenr == 20) {       /* processed 20 lines? */
       printf("press any key to quit, or [ENTER] to continue:\n");
       while ((q = getchar()) != '\n' && q != EOF  ) {
         return 0;
       }
       linenr = 0;            /* reset line counter */
    }
  }
  return 0;
}

In particular, try to avoid reading from the same stream at several
places in the program (especially in nested loops) -- if can be
avoided.  This only unnecessarily complicates things, and there's a
high potential it'll bite you sooner or later.
What you need is essentially a minimal version of 'cat' with an added
line counter, and some test logic based on that counter to stop and
wait at multiples of 20.

Almut


P.S.  Don't mean to spoil your pleasure to discover things yourself,
but I think, in this case, a piece of code is just clearer than wordy
explanations...
(I know I tend to provide more or less finished solutions too soon,
which might not always be desirable from a didactic point of view.
If you don't like it, just let me know, and I'll try to remember... :)


More information about the Programming mailing list