Sunday, August 28, 2011

Exercise 1-23 (continued)

Exercise 1-23  Write a program to remove all comments from a C program.  Don't forget to handle quoted strings and character constants properly.  C comments do not nest.

#include <stdio.h>

static int buffer_slash = 0;

void remove_comments(char current, char last)
{
  static int comment = 0;
  static int skip = 0;

  if (skip)
    skip = 0;    /* Avoid what happens when you have / * / in sequence */
  else if (comment == 0)
  {
    if (current == '/')
      buffer_slash = 1;
    else if (last == '/' && current == '*')
    {
      buffer_slash = 0;
      comment = 1;
      skip = 1;
    }
    else
    {
      if (buffer_slash)
      {
        buffer_slash = 0;
        putchar('/');
      }
      putchar(current);
    }
  }
  else  /* comment == 1 */
  {
    if (last == '*' && current == '/')
      comment = 0;
  }
}

void remove_double_quotes(char current, char last)
{
  static int quotes_open = 0;

  if (quotes_open)
    putchar(current);
  else
    remove_comments(current, last);

  if (current=='\"')
    quotes_open = !quotes_open;
}

void parse_single_quotes(char current, char last)
{
  static int single_quote_open = 0;

  /* If we're in single quotes, then " does not open a string literal. */

  if (single_quote_open)
    remove_comments(current, last);
  else
    remove_double_quotes(current, last);

  if ((last!='\\') && (current=='\''))
      single_quote_open = !single_quote_open;
}

int main(void)
{
  int last = 0;
  int current;

  while (current = getchar(), current!=EOF)
  {
    parse_single_quotes(current, last);
    last = current;
  }

  if (buffer_slash)
    putchar('/');

  return 0;
}

No comments:

Post a Comment