Wednesday, August 17, 2011

Exercise 1-17

Exercise 1-17  Write a program to print all input lines that are longer than 80 characters.

#include <stdio.h>

#define MAXLINE 80

int main(void)
{
  int c;

    /* bufpos == MAXLINE means we have filled the buffer and need to print it,
     * bufpos == MAXLINE+1 means we have already printed it. */

  unsigned int bufpos = 0;
  char buffer[MAXLINE];

  while (c=getchar(), c!=EOF)
  {
    if (bufpos<MAXLINE)
    {
      if (c=='\n')
        bufpos = 0;
      else
        buffer[bufpos++]=c;
    }
    else
    {
      if (bufpos==MAXLINE)
      {
        for (bufpos=0; bufpos<MAXLINE;++bufpos)
          putchar(buffer[bufpos]);
        bufpos=MAXLINE+1;
      }

      putchar(c);
      if (c=='\n')
        bufpos = 0;
    }
  }

  return 0;
}

No comments:

Post a Comment