1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140
| #include<stdio.h>
#include <ctype.h>
#include <string.h>
#include <stdlib.h>
char c;
char buffer[100];
char *motcle[]=
{"program","var","integer","real","boolean","begin","true","while","writeln*","readln",
"if","then","end","else","false"};
char *separa[]=
{";",":",",",":=","'","/","(",")","<>",">","+","-","."};
char *ident[100];//identifiicateur
int k,i,p,nident=0;
//:declaration de struct*********************
struct Ttoken{
int type;//afficher type ex:si motcle=1 si identificateur type=2.....
int pos;//position de se mot cle ou se identificateur ou separateur
dans le tableau
int li;//la ligne ou se trouve se mot dans le texte a analyser
int col;//la colone ou se trouve se mot dans le texte a analyser
} token;
//***********struct pour afficher le
code******************************
// la foncton qui cherche la position *************************
int trouv(char *t[],char *s,int n)
{
int j,pos=-1;
for(j=0;j<n;j++)
{if(strcmp(t[j],s)==0)
pos= j;
}
return pos;
}//********************************************
int main(void)
{
FILE *f,*fs;
int etat = 0;
int ib=0;
f=fopen("tp1.pas","r");//le texte a analyser
fs=fopen("tp10.txt","w");//le texte source simplifier
while(fread(&c,sizeof(char),1,f))
{
if (c!='\r')
{
switch(etat)
{case 0:
{
if (isalpha(c))
{
etat = 1;
i=0;
buffer[i]=c;
i++;
ib++;
continue;
}
}
case 1:
{
if (isalnum(c)) {
buffer[i]=buffer[i]+c;
i++;
ib++;
} else {
p=trouv(motcle,buffer,13);
if(p!=-1){
token.type=1;
token.pos=p;
token.li=0;
token.col=0;
fwrite(&token,sizeof(token),1,fs);
}
else
{
p=trouv(ident,buffer,nident);
if(p!=-1){
token.type=2;
token.pos=p;
token.li;
token.col;
fwrite(&token,sizeof(token),1,fs);
}
else
{
ident[nident]=malloc(sizeof(buffer[i]));
strcpy(ident[nident],buffer);
buffer[i]='\0';
token.type=2;
token.pos=p;
token.li;
token.col;
fwrite(&token,sizeof(token),1,fs);
nident=nident+1;
}}
}
etat = 0;
ungetc(c,f);
}
token.col++;
}}
else token.li++;
}
fclose(f);
fclose(fs);
} |
Partager