forked from jelly9/C-Project
-
Notifications
You must be signed in to change notification settings - Fork 0
/
commentConvert.c
154 lines (133 loc) · 2.15 KB
/
commentConvert.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
#include "commentConvert.h"
status_t gStatus = NORMAL_STATUS;
//处理正常状态
static void doNormalStatus(FILE* in, FILE* out)
{
int first = fgetc(in);
int second = 0;
assert(in);
assert(out);
switch(first){
case '/' :
second = fgetc(in);
if( '*'== second){
fputc('/', out);
fputc('/', out);
gStatus = C_STATUS;
}else
if('/' == first){
fputc(first, out);
fputc(first, out);
gStatus = CPP_STATUS;
}
else{
fputc(first, out);
fputc(first, out);
}
break;
case EOF:
gStatus = END_STATUS;
break;
default:
fputc(first, out);
break;
}
}
//处理c状态
static void doCStatus(FILE* in, FILE* out)
{
int first = fgetc(in);
int second = 0;
int third = 0;
assert(in);
assert(out);
switch(first){
case '*' :
second = fgetc(in);
if('/' == second){
third = fgetc(in);
if('\n' == third){
fputc('\n', out);
}else{
fputc('\n', out);
ungetc(third, in);
}
gStatus = NORMAL_STATUS;
}
else{
fputc(first, out);
ungetc(second, in);
}
break;
case EOF :
gStatus = END_STATUS;
break;
case '\n':
fputc(first, out);
fputc('/', out);
fputc('/', out);
break;
default:
fputc(first, out);
break;
}
}
//处理cpp状态
static void doCppStatus(FILE* in, FILE* out)
{
int first = fgetc(in);
assert(in);
assert(out);
switch(first){
case '\n' :
fputc(first, out);
gStatus = NORMAL_STATUS;
break;
case EOF :
gStatus = END_STATUS;
break;
default:
fputc(first, out);
break;
}
}
//状态机
static void statusMachine(FILE* in, FILE* out)
{
assert(in);
assert(out);
while(END_STATUS != gStatus){//根据状态进入相应逻辑
switch(gStatus){
case NORMAL_STATUS:
doNormalStatus(in, out);
break;
case C_STATUS :
doCStatus(in, out);
break;
case CPP_STATUS :
doCppStatus(in, out);
break;
case END_STATUS :
break;
default:
break;
}
}
}
//注释转换开始
void convertBagin()
{
FILE* in = fopen(INPUT_FILE, "r");
FILE* out = fopen(OUTPUT_FILE, "w");//打开要转换的文件
if(NULL == in){
perror("fopen");
exit(1);
}
if(NULL == out){
perror("fopen");
exit(2);
}
statusMachine(in, out);//进入状态机开始转换
fclose(in);
fclose(out);//关闭文件
}