Wednesday, 4 January 2012

Macro Processor in C


Macro Processor in C

Question

To Implement a Macro Processor in C language.

Program

#include "stdio.h"
#include "string.h"
#include "stdlib.h"
void main()
{
FILE *fp1,*fp2,*fp3,*fp4;
char opcode[50],name[50],def[50];
fp1=fopen("source.dat","r");
fp2=fopen("define.dat","w");
fp3=fopen("name.dat","w");
fp4=fopen("out.dat","w");
while(!feof(fp1))
{
fscanf(fp1,"%s",opcode);
strcpy(name,opcode);
fscanf(fp1,"%s",opcode);
if(strcmp(opcode,"MACRO")==0)
{
fprintf(fp3,"%s\n",name);
fprintf(fp2,"%s\n",name);
while(strcmp(opcode,"MEND")!=0)
{
fprintf(fp2,"%s\n",opcode);
fscanf(fp1,"%s",opcode);
}
fprintf(fp2,"MEND\n");
}
}
fclose(fp1);
fclose(fp2);
fclose(fp3);
fp1=fopen("source.dat","r");
fp3=fopen("name.dat","r");
fp2=fopen("define.dat","r");
fscanf(fp2,"%s",def);
while(!feof(fp1))
{
fscanf(fp1,"%s",opcode);
fscanf(fp3,"%s",name);
if(strcmp(opcode,name)==0)
{
fscanf(fp1,"%s",opcode);
if(strcmp(opcode,"MACRO")==0)
{
while(strcmp(opcode,"MEND")!=0)
{
fscanf(fp1,"%s",opcode);
}
}
}
else
{
strcpy(name," ");
if(strcmp(opcode,def)==0)
{
fscanf(fp2,"%s",def);
if(strcmp(def,"MACRO")==0)
fscanf(fp2,"%s",def);
while(strcmp(def,"MEND")!=0)
{
fprintf(fp4,"%s\n",def);
fscanf(fp2,"%s",def);
}
fscanf(fp2,"%s",def);
}
else if(strcmp(opcode,"END")==0)
{
fprintf(fp4,"END\n");
break;
}
else
{
fprintf(fp4,"%s\n",opcode);
}

}
}
}

Download Source Code


source.dat

ADDA MACRO
CLEAR A
ADD 05
MEND
SUBA MACRO
CLEAR A
SUB 05
MEND
COPY START 0
CLEAR X
ADDA
SUBA
END

define.dat

ADDA
MACRO
CLEAR
A
ADD
05
MEND
SUBA
MACRO
CLEAR
A
SUB
05
MEND

name.dat

ADDA
SUBA

out.dat

COPY
START
0
CLEAR
X
CLEAR
A
ADD
05
CLEAR
A
SUB
05
END

0 comments: