Wednesday, 4 January 2012

Single Pass Assembler in C


Single Pass Assembler in C

Question

To implement a single Pass assembler in C language.

Program

#include "stdio.h"
#include "string.h"
#include "stdlib.h"
int count[20];
void wordcount()
{
FILE *f3;
f3=fopen("input.c","r");
int word=0,i=1;
char c;
while((c=getc(f3))!=EOF)
{
if(c==' ')
word+=1;
if(c=='\n')
{
word+=1;
count[i] = word;
printf("\n No.of words in line %d is %d",i,word);
i++;
word=0;
}
}
fclose(f3);
}
void main()
{
char lbl[10],mne[10],opd[10],mne1[10],opd1[10],opd2[10],val[10],adr1[10];
int locctr,linenumber,f;
FILE *f1,*f2,*f3,*f4;
f1=fopen("input.c","r");
f2=fopen("symtab.c","w+");
f4=fopen("inter.c","w");
printf("\n WORD COUNT OF THE PROGRAM IS :");
wordcount();
printf("\n Source \t Code \t Opcode \t Object code\n");
fscanf(f1,"%s %s %x",lbl,mne,&locctr);
linenumber=2;
while(!feof(f1))
{
if(count[linenumber]==3)
{
fscanf(f1,"%s %s %s",lbl,mne,opd);
fprintf(f4,"%x \t %s \t %s \t %s\n",locctr,lbl,mne,opd);
fprintf(f2,"%x \t %s \t %s\n",locctr,lbl,opd);
if(strcmp(mne,"RESB")==0 || strcmp(mne,"RESW")==0)
{
printf("%s \t %s \t 00 \t 0000\n",lbl,mne);
}
else
printf("%s \t %s \t 00 \t 000%s\n",lbl,mne,opd);
}
if(count[linenumber]==2)
{
fscanf(f1,"%s %s",mne,opd);
fprintf(f4,"%x \t %s \t %s\n",locctr,mne,opd);
printf("%s \t %s \t",mne,opd);
f3=fopen("opcode.c","r");
while(!feof(f3))
{
fscanf(f3,"%s%s\n",mne1,opd1);
if(strcmp(mne,mne1)==0)
printf("%s \t",opd1);
}
fclose(f3);
f=0;
rewind(f2);
//f2=fopen("symtab.c","r");
while(!feof(f2))
{
fscanf(f2,"%s %s %s",adr1,opd2,val);
if(strcmp(opd,opd2)==0)
{
printf("%s\n",adr1);
f=1;
}
}
if(f=0)
printf("0000\n");
}
if(count[linenumber]==1)
{
fscanf(f1,"%s\n",mne);
fprintf(f4,"%x %s\n",locctr,mne);
}
linenumber+=1;
if(strcmp(mne,"WORD")==0)
locctr+=3;
else if(strcmp(mne,"BYTE")==0)
locctr+=strlen(opd);
else if(strcmp(mne,"RESW")==0)
locctr+=3*(atoi(opd));
else if(strcmp(mne,"RESB")==0)
locctr+=atoi(opd);
else
locctr+=3;
}
fclose(f1);
fclose(f2);
fclose(f4);
}

Download Source Code

0 comments: