1 Star 1 Fork 0

刘司元 / C语言分词器

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
main.c 1.72 KB
一键复制 编辑 原始数据 按行查看 历史
刘司元 提交于 2023-08-17 03:31 . update main.c.
#include "cscanner.h"
// 分词器小功能
// 过滤掉字符流中的空格, 注释等, 并将其划分为一个个的 token, 生成 token 序列
static void run(const char *source) {
initScanner(source);
int line = -1;
while (1) {
Token token = scanToken();
if (token.line != line) {
printf("%4d ", token.line);
line = token.line;
} else {
printf(" | ");
}
printf("%2d '%.*s'\n", token.type, token.length, token.start);
if (token.type == TOKEN_EOF) {
break;
}
}
}
// 用户每输入一行代码, 分析一行代码, 并将结果输出
static void repl() {
char source[50];
while(fgets(source, 50, stdin)) {
size_t len = strlen(source);
source[len - 1] = '\0';
run(source);
}
}
// 将文件的内容读入内存, 并在末尾添加 '\0'
static char *readFile(const char *path) {
FILE *file = fopen(path, "r");
int c, count = 0;
while((c = fgetc(file)) != EOF) {
count++;
}
char *source = (char *) malloc((count + 1) * sizeof(char));
rewind(file);
for(int i = 0; (c = fgetc(file)) != EOF; i++) {
source[i] = (char)c;
}
source[count] = '\0';
return source;
}
// 分析传入的 .c 文件, 并将结果输出
static void runFile(const char *path) {
char *source = readFile(path);
// puts(source);
run(source);
free(source);
}
int main(int argc, char *argv[]) {
if (argc == 1) {
repl();
} else if (argc == 2) {
runFile(argv[1]);
} else {
fprintf(stderr, "Usage: scanner [path]\n");
exit(1);
}
return 0;
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
C
1
https://gitee.com/liu-siyuan888/cscanner.git
git@gitee.com:liu-siyuan888/cscanner.git
liu-siyuan888
cscanner
C语言分词器
master

搜索帮助

344bd9b3 5694891 D2dac590 5694891