[prog] C problem I am unable to solve

Angelina Carlton brat at magma.ca
Thu May 12 03:18:21 EST 2005


Hello 

one of the last excercise I have in this chapter is to write
a program that displays lines from a a file

/* Write a program that displays the contents of a file 20
   lines at a time, after which it pauses and waits for
   the user to enter q to quit or any other key to keep
   going.*/

So my program asks for a file, checks it exists and and 
makes sure it has an EOF

the function I use to do the reading is giving me problems
though, it seems using either fgets or getc I can read up 
to 20 lines but the second time it jumps to 40 lines at a
time without asking at the 20 line mark,

int read_file(FILE *inputfile)
{

  int i; /* number of lines to display at one time */
  char c;
  char q;

  while(! (feof(inputfile)) ) { /* until the end of the file*/
    for (i = 0; i <= 19; ++i) {
      while ( (c = getc(inputfile)) != '\n' )
        putc(c, stdout); /* display the line */
        putc('\n', stdout);
      if(i == 19) { /* stop at 20 */
        printf("press 'q' to quit, any other key to continue:\n");
        scanf("%c", &q);
        if (q == 'q') {
          return 0;
        }
      }
    }
  }
  return 0;
}

here is also the fgets version of the same function:

 while(! (feof(inputfile)) ) { /* until the end of the file*/
    for (i = 0; i <= 19; ++i) {
      fgets(linebuffer, sizeof(linebuffer), inputfile);
      fputs(linebuffer, stdout); /* display the line */
      if(i == 20) { /* stop at 20 */
        printf("press 'q' to quit, any other key to continue:\n");
        scanf("%c", &q);
        if (q == 'q') {
          return 0;
        }
      } 
     }    
    }
return 0;
}

Sorry the indenting is sort of mangled by mutt, but hopefully you see
the approach I took.

Either way, the program reads the first 20 lines and waits, if I press
q it quits (so far so good) 

If I then press anyother key, it displays line 20 to line 60, and then
waits , it does display the printf at line 40 and I see "press q to
quit" but it skips any prompting and then goes through the file
prompting every 40 lines instead of 20

I *think* this is something to do with while loops testing at the end
of the block, but cant seem to figure  out how to fix this so I am
asking for a tip or advice how to properly approach problems like
this.

Also it goes into a nice infinate loop at the end :-) but I want to
fix the first problem first.  

Thanks! 


-- 
Angelina Carlton


More information about the Programming mailing list