您需要为特定文件类型编写解析器和词法分析器并保存必要的信息。但是从测试文件中获取数字列表甚至都不起作用
测试.txt
port (
3, 5, 7,
9, 11, 13,
15, 17, 19
);
对于词法分析,我使用简单的规则
词汇表
%{
#include <stdio.h>
#include "y.tab.h"
%}
delim [ \t\n]
ws {delim}+
digit [0-9]
number {digit}+
sym [a-zA-z]
%%
port { return PORT; }
"(" { return OBRACE; }
")" { return CBRACE; }
";" { return SEMICOLON; }
"," { return COMMA; }
{delim} {}
{number} { yylval.ival = atoi(yytext); return NUMBER; }
%%
int yywrap (void)
{
return 1;
}
你必须使用递归来解析
yacc.y
%{
#include <stdio.h>
#include <stdlib.h>
extern int yylex();
extern char *yytext;
int ports[9];
int curPort = 0;
%}
%union {
int ival;
char *cval;
}
%token NUMBER;
%token PORT OBRACE CBRACE COMMA SEMICOLON
%type <ival> exp NUMBER
%%
commands: /* empty */
| commands command
;
command:
ports_set
;
ports_set:
OBRACE exp CBRACE SEMICOLON
;
exp:
NUMBER { $$ = $1; }
| exp COMMA NUMBER { ports[curPort++] = $3; }
;
%%
extern FILE *yyin;
int main (int argc, char **argv)
{
yyin = fopen("text.txt", "r");
do {
yyparse();
} while (!feof(yyin));
fclose(yyin);
int i;
for (i = 0; i < 9; ++i) {
printf("port %d: %d\n", i, ports[i]);
}
}
int yyerror(char const *s)
{
printf("ERROR: %s\n", s);
return 0;
}
结果,我得到一个错误和一个零值的端口数组
$ ./test.exe
ERROR: syntax error
port 0: 0
port 1: 0
port 2: 0
port 3: 0
port 4: 0
port 5: 0
port 6: 0
port 7: 0
port 8: 0