// // hint for homework #3 -- uses StreamTokenizer to count // lines of C-style source // import java.io.* ; public class CountCLines { // command line argument is infile // counts lines of infile, ignoring any that contain only // whitespace or (part of a) C-style comment. public static void main(String[] args) { if (args.length < 1) { System.exit(-1) ; } StreamTokenizer st = null ; // build StreamTokenizer object reading from // an input stream whose source is infile try { st = new StreamTokenizer( new FileReader(args[0])) ; } catch (FileNotFoundException e) { System.out.println("Input file " + args[0] + " not found") ; System.exit(-1) ; } // set up StreamTokenizer: // reset to turn off all default behaviors st.resetSyntax() ; // group alphanumerics into words st.wordChars('a', 'z') ; st.wordChars('A', 'Z') ; st.wordChars('0', '9') ; // ignore whitespace st.whitespaceChars(0, ' ') ; // parse quoted strings (double quotes) st.quoteChar('"') ; // ignore C-style comments st.slashStarComments(true) ; int prevLine = 0 ; int thisLine = 0 ; int count = 0 ; try { int tokenType = st.nextToken() ; while (tokenType != StreamTokenizer.TT_EOF) { thisLine = st.lineno() ; if (thisLine != prevLine) { count++ ; prevLine = thisLine ; } tokenType = st.nextToken() ; } } catch (IOException e) { System.out.println("I/O error during parsing") ; } System.out.println("line count, " + "excluding C comments and whitespace, is " + count) ; } }