2 * Copyright (c) 1999 Apple Computer, Inc. All rights reserved.
4 * @APPLE_LICENSE_HEADER_START@
6 * "Portions Copyright (c) 1999 Apple Computer, Inc. All Rights
7 * Reserved. This file contains Original Code and/or Modifications of
8 * Original Code as defined in and that are subject to the Apple Public
9 * Source License Version 1.0 (the 'License'). You may not use this file
10 * except in compliance with the License. Please obtain a copy of the
11 * License at http://www.apple.com/publicsource and read it before using
14 * The Original Code and all software distributed under the License are
15 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
16 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
17 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT. Please see the
19 * License for the specific language governing rights and limitations
22 * @APPLE_LICENSE_HEADER_END@
27 * Removes all comments and (optionally) whitespace from an input file.
28 * Writes result on stdout.
32 #include <ctype.h> /* for isspace */
36 * State of input scanner.
40 IS_SLASH
, // encountered opening '/'
41 IS_IN_COMMENT
, // within / * * / comment
42 IS_STAR
, // encountered closing '*'
43 IS_IN_END_COMMENT
// within / / comment
46 static void usage(char **argv
);
49 main(int argc
, char **argv
)
53 input_state_t input_state
= IS_NORMAL
;
55 int remove_whitespace
= 0;
61 for (arg
= 2; arg
< argc
; arg
++) {
62 switch (argv
[arg
][0]) {
71 fp
= fopen(argv
[1], "r");
73 fprintf(stderr
, "Error opening %s\n", argv
[1]);
78 bufchar
= getc_unlocked(fp
);
83 switch (input_state
) {
87 * Might be start of a comment.
89 input_state
= IS_SLASH
;
91 if (!(remove_whitespace
&& isspace(bufchar
))) {
92 putchar_unlocked(bufchar
);
101 * Start of normal comment.
103 input_state
= IS_IN_COMMENT
;
108 * Start of 'to-end-of-line' comment.
110 input_state
= IS_IN_END_COMMENT
;
115 * Not the start of comment. Emit the '/'
116 * we skipped last char in case we were
117 * entering a comment this time, then the
120 putchar_unlocked('/');
121 if (!(remove_whitespace
&& isspace(bufchar
))) {
122 putchar_unlocked(bufchar
);
124 input_state
= IS_NORMAL
;
130 if (bufchar
== '*') {
132 * Maybe ending comment...
134 input_state
= IS_STAR
;
143 * End of normal comment.
145 input_state
= IS_NORMAL
;
150 * Still could be one char away from end
157 * Still inside comment, no end in sight.
159 input_state
= IS_IN_COMMENT
;
164 case IS_IN_END_COMMENT
:
165 if (bufchar
== '\n') {
167 * End of comment. Emit the newline if
170 if (!remove_whitespace
) {
171 putchar_unlocked(bufchar
);
173 input_state
= IS_NORMAL
;
176 } /* switch input_state */
177 } /* main read loop */
188 printf("usage: %s infile [r(emove whitespace)]\n", argv
[0]);