Wednesday, August 17, 2011

Exercise 1-18 (continued)

Exercise 1-18  Write a program to remove trailing blanks and tabs from each line of input, and to delete entirely blank lines.

This program uses dynamic memory allocation to store the blanks.  Therefore, it will store any number of blanks until the computer runs out of memory.  However, it will be far slower than the statically allocated versions.

#include <stdio.h>
#include <stdlib.h>

size_t buffer_size = 0;
char *buffer = NULL;

void clear_buffer(void)
{
  free(buffer);
  buffer = NULL;
  buffer_size = 0;
}

void flush(void)
{
  size_t i;
  for (i = 0; i < buffer_size; ++i)
    putchar(buffer[i]);

  clear_buffer();
}

void push(char c)
{
  void *newbuffer;
  newbuffer = realloc(buffer, buffer_size+1);
  if (newbuffer == NULL)
  {
    printf("Out of memory.\n");
    free(buffer);
    exit(1);
  }

  buffer = newbuffer;
  buffer[buffer_size] = c;
  buffer_size++;
}

void display(char c)
{
  flush();
  putchar(c);
}

void strip(char c)
{
  switch(c)
  {
  case ' ':
  case '\t':
    push(c);
    break;

  case '\n':
    clear_buffer();
    putchar(c);
    break;

  default:
    display(c);
    break;
  }
}

int main(void)
{
  int c;
  int newline = 1;

  while (c=getchar(), c!=EOF)
  {
    if (!newline || c!='\n')
    {
      newline = 0;
      strip(c);
    }

    if (c=='\n')
      newline = 1;
  }

  clear_buffer();

  return 0;
}

No comments:

Post a Comment