//main.c
#include <stdio.h>
#include <ctype.h>
#define MAXLINE 1024
#define SKIPSPACE(p) while(isspace(*p)) p++;
FILE *yyin=NULL;
char srcbuf[MAXLINE<<1];
int lineno=0; //当前行
static void ShowHelp(void);
static void ShowError(char *msg);
static void ShowWarning(char *msg);
static char* SkipComment(char* p);
static void GetNextLine(void);
int main(int argc, char *argv[], char *envp[])
{
if(argc<2) {
ShowHelp();
return 0;
}
if((yyin=fopen(argv[1],"r"))==NULL) {
ShowError("File Not Found!");
return 0;
}
while(!feof(yyin)) {
GetNextLine();
printf("%4d: %s/n", lineno, srcbuf);
}
fclose(yyin);
return 0;
}
static void ShowHelp(void)
{
printf("语法:RemoveComment [file]/n");
}
static void ShowError(char *msg)
{
printf("Error: %s/n", msg);
//exit(1);
}
static void ShowWarning(char *msg)
{
printf("Warning: %s/n", msg);
}
static char* SkipComment(char* p)
{
p++;
while(1) {
while((*p!='/n')&&(*p!=0)) {
if(*p++=='*') {
if(*p++=='/') {
//if(*p<=32) {
// printf("Debug In SkipComment: %d./n", *p);
//} else {
// printf("Debug In SkipComment: Char Of %c./n", *p);
//}
return p;
}
}
}
//重些获取一个新行
p=srcbuf+MAXLINE;
if(fgets(p, MAXLINE, yyin)) {
lineno++;
} else {
ShowError("源文件在/* */注释中结束!");
break;
}
}
return NULL;
}
static void GetNextLine(void)
{
register char *p, *tmp;
char c;
p=tmp=srcbuf;
*p=0;
if(yyin==NULL) return;
//if(feof(yyin)) return;
if(fgets(p,MAXLINE,yyin)!=NULL) {
lineno++;
//SKIPSPACE(tmp);
while(((c=*tmp++)!='/n')&&(c!=0)) {
if(c=='/') {
if(*tmp=='/') break; // //形式的注释,本行处理结束
if(*tmp=='*') { //如果为 /**/形式的注释
if((tmp=SkipComment(tmp))==NULL) {
break;
}
continue;
}
}
*p++=c;
}
*p=0;
}
}
实现:
1、剔出//与/* */注释
2、加行号
收获:
1、所有系统带.h文件用<>进行#include
2、读取缓冲区为至少两个MAXLINE大小,是因为跳过/**/的处理需要临时缓冲区的缘故
参考资料:
1、MUDOS v22.2b14源码
2、《C语言的科学和艺术》