以下两则代码均是在向论坛上的高手们学习之后模仿出的结果,而自己之前写的那叫个臭呀!
代码1
1
/**//*
2
* 用状态机实现对代码中注释的清除.
3
*/
4
5
#include <stdio.h>
6
#include <string.h>
7
8
#define SCREEN
9
10
void initialize_fsm(char fsm[7][256]);
11
12
int main()
13

{
14
int ch , temp = 0 ;
15
int state = 0;
16
char fsm[7][256];
17
18
FILE *pfin ;
19
if ((pfin = fopen("sweep-comments.txt","r")) == NULL)
20
{
21
printf("can not open the file");
22
exit(0);
23
}
24
25
#ifdef SCREEN
26
#define OUT stdout
27
#else
28
FILE *pfout;
29
pfout = fopen("result.txt","w");
30
#define OUT pfout
31
#endif
32
33
initialize_fsm(fsm);
34
35
#pragma region FSM /**////尝试#pragma region功能. Visual C++ 2005
36
37
while ((ch = fgetc(pfin)) != EOF)
38
{
39
state = fsm[state][ch];
40
41
if ( state != 2 && ch !='*' && temp == '/')
42
fputc(temp,OUT);
43
44
temp = ch;
45
46
switch(state)
47
{
48
/**//*0,5,6执行同一个动作*/
49
case 5:
50
case 6:
51
case 0:
52
fputc(ch,OUT);
53
break;
54
case 7:
55
state = 0;
56
break;
57
}
58
59
if(state != 1)
60
temp=0;
61
}
62
#pragma endregion
63
}
64
65
void initialize_fsm(char fsm[7][256])
66

{
67
int lenth = sizeof(char)*256;
68
69
memset(fsm[0],0,lenth);
70
memset(fsm[1],0,lenth);
71
memset(fsm[2],2,lenth);
72
memset(fsm[3],3,lenth);
73
memset(fsm[4],3,lenth);
74
memset(fsm[5],5,lenth);
75
memset(fsm[6],5,lenth);
76
77
fsm[0]['"'] = 5;
78
fsm[0]['/'] = 1;
79
fsm[1]['/'] = 2;
80
fsm[1]['*'] = 3;
81
fsm[2]['\n'] = 0;
82
fsm[3]['*'] = 4;
83
fsm[4]['/'] = 7;
84
fsm[5]['\\'] = 6;
85
fsm[5]['"'] = 0;
86
}
87
代码2
1
%
{
2
/**//*
3
*用lex实现清除代码注释
4
*/
5
void comment(int style);
6
void string_constant();
7
const int singalline =0, multiline =1;
8
9
%}
10
11
12
%%
13
14
"/*"
{comment(multiline );}
15
"//"
{comment(singalline);}
16
"\"" {string_constant();}
17
.|\n
{fprintf(yyout,"%c",*yytext);}
18
19
%%
20
21
int main(int argc,char *argv[])
22

{
23
FILE *pfin ,*pfout;
24
if ((pfin = fopen (argv[1],"r")) ==NULL)
25
{
26
printf("can not open the file\n");
27
exit (1);
28
}
29
pfout = fopen("output.txt","w");
30
31
yyin = pfin;
32
yyout = pfout;
33
34
yylex();
35
36
return 0;
37
}
38
39
void string_constant()
40

{
41
int ch ;
42
43
fprintf(yyout,"%c",*yytext);
44
45
while ( (ch = input()) != EOF)
46
{
47
if (ch == '\\')
48
{
49
fprintf(yyout,"%c",ch);
50
ch = input();
51
fprintf(yyout,"%c",ch);
52
53
continue;
54
}
55
56
if (ch == '\"')
57
{
58
fprintf(yyout,"%c",ch);
59
break;
60
}
61
62
fprintf(yyout,"%c",ch);
63
}
64
}
65
66
void comment(int style)
67

{
68
int ch , prev=0;
69
if (style == multiline)
70
{
71
while ( (ch = input()) != EOF )
72
{
73
if (prev == '*' && ch == '/')
74
return ;
75
76
prev = ch;
77
}
78
79
return ;
80
}
81
else
82
{
83
while ( (ch = input()) != EOF )
84
{
85
if (ch == '\n')
86
{
87
fprintf(yyout,"%c",'\n');
88
return ;
89
}
90
}
91
}
92
}
93
int yywrap()
94

{
95
return 1;
96
}
97
posted on 2009-05-07 14:21
zhaoyg 阅读(645)
评论(0) 编辑 收藏 引用 所属分类:
小代码