C语言实现词法分析

本程序中,事先建立一个带有注释的文件,这里建立的是“a1.c”,最后的输出写入“a.txt”文件中。
#include <stdio.h>
FILE *in,*out;
char ch1,ch2;
int main()
{
    if ((in=fopen("a1.c","r"))==NULL)
        printf("file a1.c can't be opened\n");
    else
    {
        if ((out=fopen("a.txt","w"))==NULL)
            printf("file a.txt can't be opened\n");
        else
        {
            fscanf(in,"%c%c",&ch1,&ch2);
            while(!feof(in))
            {
                if(ch1=='/'&&ch2=='/'){
                    while(ch1!='\n'){
                        ch1=fgetc(in);
                    }
                    fprintf(out,"\n");
                    fscanf(in,"%c%c",&ch1,&ch2);
                }
                else if(ch1=='/'&&c
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
C-Minus 的词法规则 (1)关键字: if else int return void while (2)专用符号: + - * / < >= == ~= = ; , ( ) [ ] { } /* */ (3)其他标记为 ID 和 NUM ,通过下列正则表达式定义: ID = letter letter* NUM = digit digit* letter = a|..|z|A|..|Z digit = 0|..|9 (4)空格由空白、换行符、制表符组成。 (5)注释由 /*...*/ 围起来,不能嵌套。 C-Minus 的语法规则 C-Minus 的 BNF 语法如下: 1. program -> declaration_list 2. declaration_list -> declaration_list declaration | declaration 3. declaration -> var_declaration | fun_declaration 4. var_declaration -> type_specifier ID; | type_specifier ID [ NUM ]; 5. type_specifier -> int | void 6. fun_declaration -> type_specifier ID ( params ) compound_stmt 7. params -> param_list | void 8. param_list -> param_list , param | param 9. param -> type_specifier ID | type_specifier ID [ ] 10. compound_stmt -> { local_declarations statement_list } 11. local_declarations -> local_declarations var_declaration | empty 12. statement_list -> statement_list statement | empty 13. statement -> expression_stmt | compound_stmt | selection_stmt | iteration_stmt | return_stmt 14. expression_stmt -> expression ; | ; 15. selection_stmt -> if ( expression ) statement | if ( expression ) statement else statement 16. iteration_stmt -> while ( expression ) statement 17. return_stmt -> return | return expression 18. expression -> var = expression | simple_expression 19. var -> ID | ID [ expression ] 20. simple_expression -> additive_expression relop additive_expression | additive_expression 21. relop -> <= | | >= | == | ~= 22. additive_expression -> additive_expression addop term | term 23. addop -> + | - 24. term -> term mulop factor | factor 25. mulop -> * | / 26. factor -> ( expression ) | var | call | NUM 27. call -> ID ( args ) 28. args -> arg_list | empty 29. arg8list -> arg_list , expression | expression 对以上每条文法规则,给出了相关语义的简短解释。 1. program -> declaration_list 2. declaration_list -> declaration_list declaration | declaration 3. dec
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值