C语言实现词法分析

本程序中,事先建立一个带有注释的文件,这里建立的是“a1.c”,最后的输出写入“a.txt”文件中。
#include 
FILE *in,*out;
char ch1,ch2;
int main()
{
    if ((in=fopen("a1.c","r"))==NULL)
        printf("file a1.c can't be opened\n");
    else
    {
        if ((out=fopen("a.txt","w"))==NULL)
            printf("file a.txt can't be opened\n");
        else
        {
            fscanf(in,"%c%c",&ch1,&ch2);
            while(!feof(in))
            {
                if(ch1=='/'&&ch2=='/'){
                    while(ch1!='\n'){
                        ch1=fgetc(in);
                    }
                    fprintf(out,"\n");
                    fscanf(in,"%c%c",&ch1,&ch2);
                }
                else if(ch1=='/'&&ch2=='*'){
                    while(ch1!='*'||ch2!='/'){
                        ch1=ch2;
                        ch2=fgetc(in);
                    }
                    fscanf(in,"%c%c",&ch1,&ch2);
                }
                else{
                    fprintf(out,"%c",ch1);
                    ch1=ch2;
                    ch2=fgetc(in);
                }
            }
            fclose(in);
            fclose(out);
        }
    }
}
 
 

你可能感兴趣的:(c/c++,编译原理,词法分析)