comments.c - randomcrap - random crap programs of varying quality
(HTM) git clone git://git.codemadness.org/randomcrap
(DIR) Log
(DIR) Files
(DIR) Refs
(DIR) README
(DIR) LICENSE
---
comments.c (1720B)
---
1 /* extract C-style comments from code */
2 #include <stdio.h>
3
4 static size_t col = 1, linenr = 1;
5
6 int
7 getnext(void)
8 {
9 int c;
10
11 c = getchar();
12 if (c == '\n') {
13 linenr++;
14 col = 1;
15 } else {
16 col++;
17 }
18
19 return c;
20 }
21
22 void
23 prefix(void)
24 {
25 /*printf("%zu:%zu:", linenr, col);*/
26 }
27
28 int
29 main(void)
30 {
31 int c, tmp;
32
33 while ((c = getnext()) != EOF) {
34 if (c == '/') {
35 if ((c = getnext()) == EOF)
36 goto end;
37 /* // comment, read until end of line */
38 if (c == '/') {
39 prefix();
40 while ((c = getnext()) != EOF) {
41 if (c == '\n')
42 break;
43 putchar(c);
44 }
45 putchar('\n');
46 if (c == EOF)
47 goto end;
48 } else if (c == '*') {
49 prefix();
50 /* block comment, read until */
51 tmp = 0;
52 while ((c = getnext()) != EOF) {
53 if (c == '\\') {
54 tmp = 1;
55 continue;
56 }
57 /* escape end of block comment */
58 if (tmp) {
59 if (c == '*') {
60 putchar(c);
61 } else {
62 putchar('\\');
63 putchar(c);
64 }
65 tmp = 0;
66 continue;
67 }
68
69 if (c == '*') {
70 if ((c = getnext()) == EOF)
71 goto end;
72 /* end of comment */
73 if (c == '/') {
74 putchar('\n');
75 break;
76 }
77 putchar('*');
78 putchar(c);
79 #if 0
80 } else if (c == '\n') {
81 putchar(c);
82 prefix();
83 #endif
84 } else {
85 putchar(c);
86 }
87 }
88 if (c == EOF)
89 goto end;
90 }
91 } else if (c == '"') {
92 /* inside string */
93 tmp = 0;
94 while ((c = getnext()) != EOF) {
95 if (tmp) {
96 tmp = 0;
97 continue;
98 }
99 /* escape sequence: ignore next character */
100 if (c == '\\')
101 tmp = 1;
102 else if (c == '"') /* end string */
103 break;
104 }
105 if (c == EOF)
106 goto end;
107 }
108 }
109 end:
110
111 return 0;
112 }