1、首先將要過濾的.c文件讀取出來。
int main()
{
char resProject[10000];
char token[20] = {0};
int pProject = 0;
FILE *fp,*fp1;
cout<<"1111"<<endl;
if((fp = fopen("E:\\bianyiyuanlishiyan\\sy1\\demo2.c","r")) == NULL)
{
cout<<"can't open this file"<<endl;
exit(0);
}
resProject[pProject] = fgetc(fp);
while(resProject[pProject] != '$')
{
pProject++;
resProject[pProject]=fgetc(fp);
}
pProject++;
resProject[pProject] = '\0';
fclose(fp);
cout<<resProject<<endl;
filter(resProject,pProject);
cout<<resProject<<endl;
}
2、過濾註釋,有單行註釋和多行註釋之分。
void filter(char r[],int pProject)
{
char tempstr[10000];
int count = 0;
for(int i = 0;i<=pProject;i++)
{
//單行註釋,直到遇到回車換行
if(r[i]=='/'&&r[i+1]=='/')
{
while(r[i]!='\n')
{
i++;
}
}
//多行註釋
if(r[i]=='/'&&r[i+1]=='*')
{
i+=2;
while(r[i]!='*'||r[i+1]!='/')
{
i++;
if(r[i]=='$')
{
printf("error");
exit(0);
}
}
i += 2;
}
if (r[i] != '\n'&&r[i] != '\t'&&r[i] != '\v'&&r[i] != '\r')
{//若出現無用字符,則過濾;否則加載
tempstr[count++] = r[i];
}
}
tempstr[count] = '\0';
strcpy(r, tempstr);
}
運行結果:
完整代碼:
#include "stdio.h"
#include "stdlib.h"
#include "string.h"
#include "iostream"
using namespace std;
void filter(char r[],int pProject)
{
char tempstr[10000];
int count = 0;
for(int i = 0;i<=pProject;i++)
{
//單行註釋,直到遇到回車換行
if(r[i]=='/'&&r[i+1]=='/')
{
while(r[i]!='\n')
{
i++;
}
}
//多行註釋
if(r[i]=='/'&&r[i+1]=='*')
{
i+=2;
while(r[i]!='*'||r[i+1]!='/')
{
i++;
if(r[i]=='$')
{
printf("error");
exit(0);
}
}
i += 2;
}
if (r[i] != '\n'&&r[i] != '\t'&&r[i] != '\v'&&r[i] != '\r')
{//若出現無用字符,則過濾;否則加載
tempstr[count++] = r[i];
}
}
tempstr[count] = '\0';
strcpy(r, tempstr);
}
int main()
{
char resProject[10000];
char token[20] = {0};
int pProject = 0;
FILE *fp,*fp1;
if((fp = fopen("E:\\bianyiyuanlishiyan\\sy1\\demo2.txt","r")) == NULL)
{
cout<<"can't open this file"<<endl;
exit(0);
}
resProject[pProject] = fgetc(fp);
while(resProject[pProject] != '$')
{
pProject++;
resProject[pProject]=fgetc(fp);
}
pProject++;
resProject[pProject] = '\0';
fclose(fp);
cout<<resProject<<endl;
filter(resProject,pProject);
cout<<resProject<<endl;
}
.c文件代碼
#include<stdio.h>
int main()
{
int i = 0;//定義一個i
if(i==0)
{
/*輸出i
123*/
printf("i:",i);
}
return 0;
}$