代码拉取完成,页面将自动刷新
#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;
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。