Home   Cover Cover Cover Cover
 

Entfernen von Kommentaren

A01.cs
using System;
using System.IO;

class Test {
  
  /* This method copies a C# program from r to w eliminating
     all comments.
  */
  static void Copy(StreamReader r, StreamWriter w) {
    int c = r.Read();
    while (c >= 0) {
      if (c == '/') {
        int c1 = r.Read();
        if (c1 == '/') {  // skip end of line comment
          do {c = r.Read();} while (c >= 0 && c != '\n');
          if (c == '\n') {c = r.Read(); w.WriteLine();}
        } else if (c1 == '*') { // skip bracket comment
          c = r.Read();
          do {
            while (c >= 0 && c != '*') c = r.Read();
            if (c >= 0) c = r.Read();
          } while (c >= 0 && c != '/');
          if (c >= 0) c = r.Read();
        } else {
          w.Write((char)c);
          c = c1;
        }
      } else {
        w.Write((char)c);
        c = r.Read();
      }
    }
  }
  
  public static void Main(string[] arg) {
    if (arg.Length == 1) {
      try {
        FileStream s1 = new FileStream(arg[0], FileMode.Open);
        FileStream s2 = new FileStream(arg[0] + ".new", FileMode.Create);
        StreamReader r = new StreamReader(s1);
        StreamWriter w = new StreamWriter(s2);
        Copy(r, w);
        r.Close(); w.Close();
      } catch (Exception) {
        Console.WriteLine("-- invalid file name");
      }
    } else Console.WriteLine("-- file name expected");
  }
}