c语言词法分析程序
时间: 2023-06-21 16:10:34 浏览: 106
c语言编写的词法分析程序.doc
以下是一个简单的 C 语言词法分析程序,它可以读取 C 语言源代码并输出每个标识符、关键字、常量和运算符:
```c
#include <stdio.h>
#include <ctype.h>
#include <string.h>
#define MAX_LENGTH 100
int main()
{
char ch, buffer[MAX_LENGTH];
FILE *fp;
int i, j, k, len;
fp = fopen("example.c", "r");
if (fp == NULL)
{
printf("Error opening file!");
return 0;
}
while ((ch = fgetc(fp)) != EOF)
{
if (isalpha(ch))
{
i = 0;
buffer[i++] = ch;
while (isalnum(ch = fgetc(fp)))
buffer[i++] = ch;
buffer[i] = '\0';
fseek(fp, -1, SEEK_CUR);
if (strcmp(buffer, "if") == 0 || strcmp(buffer, "else") == 0 || strcmp(buffer, "while") == 0 || strcmp(buffer, "for") == 0)
printf("%s is a keyword\n", buffer);
else
printf("%s is an identifier\n", buffer);
}
else if (isdigit(ch))
{
i = 0;
buffer[i++] = ch;
while (isdigit(ch = fgetc(fp)))
buffer[i++] = ch;
buffer[i] = '\0';
fseek(fp, -1, SEEK_CUR);
printf("%s is a constant\n", buffer);
}
else if (ch == '+' || ch == '-' || ch == '*' || ch == '/' || ch == '>' || ch == '<' || ch == '=' || ch == '&' || ch == '|')
{
if (ch == '>' || ch == '<' || ch == '=')
{
if ((ch = fgetc(fp)) == '=')
printf("%c%c is a relational operator\n", buffer[0], ch);
else
{
fseek(fp, -1, SEEK_CUR);
printf("%c is an arithmetic operator\n", buffer[0]);
}
}
else if (ch == '&' || ch == '|')
{
if ((ch = fgetc(fp)) == buffer[0])
printf("%c%c is a logical operator\n", buffer[0], ch);
else
{
fseek(fp, -1, SEEK_CUR);
printf("%c is an invalid operator\n", buffer[0]);
}
}
else
printf("%c is an arithmetic operator\n", ch);
}
}
fclose(fp);
return 0;
}
```
该程序使用标准 C 库中的函数来读取源代码并从中提取标识符、关键字、常量和运算符。程序通过逐个字符读取源代码并根据字符的类型进行处理。如果字符是字母,则将其存储在缓冲区中,并读取后续的字母或数字,直到遇到非字母数字字符为止。然后,程序将缓冲区中的内容与关键字列表进行比较,以确定是否为关键字。如果不是关键字,则认为它是标识符。
如果字符是数字,则程序将其存储在缓冲区中,并读取后续的数字,直到遇到非数字字符为止。然后,程序将缓冲区中的内容视为常量。
如果字符是运算符,则程序将其与可能的后续字符进行比较以确定其是何种类型的运算符,例如算术运算符、关系运算符或逻辑运算符。
阅读全文