Code:
#include<stdio.h>
#include<conio.h>
#include<string.h>
struct source
{
char lbl[10];
char opc[10];
char op[10];
};
struct res
{
char lbl[10];
char opc[10];
char op[10];
int add;
};
struct symtab
{
char lbl[20];
int add;
};
struct symtab t[20],t1[20];
struct res r[20],r1[20];
struct source s[20],s1[20];
int n;
void create()
{
int i=0,f=0;
FILE *fp;
fp=fopen("Input2","w+");
//f=1;
for(i=0;i<n;i++)
{
// if(f==1)
// fp=fopen("Input.dat","a");
printf("Please enter label #%d: ",i+1);
// fflush(stdin);
scanf("%s",&s[i].lbl);
printf("Please enter opcode #%d: ",i+1);
//fflush(stdin);
scanf("%s",&s[i].opc);
printf("Please enter operand #%d: ",i+1);
//fflush(stdin);
scanf("%s",&s[i].op);
fwrite(&s[i],sizeof(s),1,fp);
}
fclose(fp);
}
void read()
{
struct source s1[20];
int i=0;
FILE *fp1;
fp1=fopen("Input2","r");
// for(i=0;i<=n;i++)
// {
// fflush(stdin);
while(fread(&s1[i],sizeof(s1),1,fp1)!=0)
{
printf("\n\nLabel : %s\tOpcode : %s\tOperand : %s ",s1[i].lbl,s1[i].opc,s1[i].op);
i++;
}
//}
fclose(fp1);
}
int x=0;
void process()
{
FILE *fp,*fp1,*fp2,*fp3,*fp4, *fp5;
int i,j,k;
struct source s2[20];
char lbl[20],opc[20],op[20],opcode[20],label1[20],opc1[20],op1[20],add1;
fp=fopen("Input2","r");
fp3=fopen("symtab2","w+");
printf("\nNow processing file : \n\n");
for(i=0;i<n;i++)
{
fread(&s2[i],sizeof(s2),1,fp);
printf("\nLabel #%d: ",i+1);
printf("%s",s2[i].lbl);
printf("\nOpcode #%d: ",i+1);
printf("%s",s2[i].opc);
printf("\nOperand #%d: ",i+1);
printf("%s",s2[i].op);
strcpy(lbl,s2[i].lbl);
strcpy(opc,s2[i].opc);
strcpy(op,s2[i].op);
if(strcmp(opc,"start")==0 || strcmp(opc,"START")==0)
{x=x+atoi(op);}
if(strcmp(opcode,"RESW")==0)
{
x=x+(atoi(op[i])*3);
}
else if(strcmp(opcode,"RESB")==0)
{
x=x+(atoi(op[i])*1);
}
else if(strcmp(opcode,"BYTE")==0)
{
x=x+1;
}
else
{
x=x+3;
}
fp2=fopen("output2","w+");
strcpy(r[i].lbl,lbl);
strcpy(r[i].opc,opc);
strcpy(r[i].op,op);
r[i].add=x;
fwrite(&r[i],sizeof(r),1,fp2);
if(lbl!="null" || lbl!="NULL")
{
strcpy(t[i].lbl,lbl);
t[i].add=x;
fwrite(&t[i],sizeof(t),1,fp3);
}
}
fclose(fp2);
fclose(fp3);
fclose(fp);
printf("Now beginning to display Output Table: \n");
fp4=fopen("output2","r");
for(k=0;k<n;k++)
{
fread(&r1[i],sizeof(r1),1,fp4);
strcpy(label1,r1[i].lbl);
strcpy(opc1,r1[i].opc);
strcpy(op1,r1[i].op);
}
printf("\n\nAdd: %d\tLabel: %s\tOpcode: %s\tOperand: %s",label1,opc1,op1);
getch();
fclose(fp4);
printf("Now beginning to display Symbol Table: \n");
fp5=fopen("symtab2","r");
for(k=0;k<n;k++)
{
fread(&t1[i],sizeof(t1),1,fp5);
strcpy(label1,t1[i].lbl);
add1=t1[i].add;
printf("\n\nLabel: %s\tAddress: %d",label1,add1);
}
fclose(fp5);
getch();
}
void main()
{
clrscr();
printf("Please enter no. of lines: ");
scanf("%d",&n);
create();
//read();
getch();
process();
getch();
}