删除C/C++中的注释-有限状态机(C语言实现)

前段时间写了一个删除c/c++源程序中的注释的程序,结构比较复杂,现在考虑用有限状态机来解决。代码没有考虑字符串、嵌套下的情况,若要考虑,还需进行少许修改。代码如下

 

#include <stdio.h> enum { CODE, COMMENT1, //“/**/”型注释 COMMENT2, //“//”型注释 }g_state=CODE; enum Input{ CH, //其他字符 CH1, // "/*" or "*/" CH2, // "//" RT, // "/n" }; Input alter(char ch, FILE *file) { char temp; if(ch=='/') { temp = fgetc(file); if(temp=='/') return CH2; else if(temp=='*') return CH1; else { fseek(file, -1, 1); return CH; } } else if(ch=='*') { temp = fgetc(file); if(temp=='/') return CH1; else { fseek(file, -1, 1); return CH; } } else if(ch=='/n') return RT; else return CH; } int main() { FILE *infile = fopen("infile.cpp", "r"); FILE *outfile = fopen("outfile.cpp", "w"); Input input; if(infile==NULL) { printf("cannot open infile!"); return -1; } char ch; ch = fgetc(infile); while(ch!=EOF) { input = alter(ch, infile); switch(g_state) { case CODE: if(input==CH || input==RT) fputc(ch, outfile); else if(input==CH1) g_state = COMMENT1; else if(input==CH2) g_state = COMMENT2; else ; break; case COMMENT1: if(input==CH1) g_state = CODE; break; case COMMENT2: if(input==RT) { fputc('/n', outfile); g_state = CODE; break; } } ch = fgetc(infile); } printf("complete!"); getchar(); fclose(infile); fclose(outfile); return 0; }  

你可能感兴趣的:(c,File,null,input,语言)