打开文件写入并在控制台中显示结果

时间:2017-04-08 10:30:21

标签: c

我是C的新手,我尝试做的是获取用户代码输入,从代码中删除所有注释,然后获取新代码并继续使用它。 所以我创建了一个删除注释的函数,将结果代码打印到文件并返回该文件。 它看起来像这样:

#include <stdio.h>

enum status {OUT, IN_STRING, LEFT_SLASH, IN_COMMENT, RIGHT_STAR, IN_CPP_COM};

FILE *trim_comments(){

    int c;
    int state = OUT;
    FILE *clean_code;
    clean_code = fopen("clean-code.c", "w+");

    while ( (c = getchar()) != EOF )
        switch ( state ) {
            case OUT:
                if ( c == '/' ) {
                    state = LEFT_SLASH;
                } else {
                    fputc(c, clean_code);
                    if ( c == '\"' )
                        state = IN_STRING;
                }
            break;

            case LEFT_SLASH :

                if ( c == '*' ) {
                    state = IN_COMMENT;
                } else if ( c == '/'){
                    state = IN_CPP_COM;
                } else {
                    fputc('/', clean_code);
                    fputc(c, clean_code);
                    state = OUT;
                }

            break;

            case IN_COMMENT :

            if ( c == '*' ) {
                state = RIGHT_STAR;
            }

            break;

            case IN_CPP_COM :
                if ( c == '\n' ) {
                    state = OUT;
                    fputc('\n', clean_code);
                }
            break;

            case RIGHT_STAR :
                if ( c == '/' ) {
                    state = OUT;
                } else if ( c != '*' ) {
                    state = IN_COMMENT;
                }
            break;

            case IN_STRING :
                if ( c == '\"' )
                    state = OUT;
                fputc(c, clean_code);
            break;

        } 

        return clean_code;

}

然后在主要的我得到文件,并希望现在将其打印到控制台:

#include <stdio.h>

FILE *trim_comments();

int main(void){

    int c;

    FILE *file = trim_comments();

    while  ( (c = fgetc(file)) != EOF ) {
        printf("%c", c);
    }

    return 0;

}

当我运行程序时,文件clean-code.c已创建,但它是空白的。我也没有在控制台中看到任何内容,程序只是等待: enter image description here

还有makefile:

myprog : par.o trim-comments.o
        gcc -g -Wall -pedantic -ansi par.o trim-comments.o -o myprog

par.o : par.c
        gcc -c -Wall -pedantic -ansi par.c -o par.o

trim-comments.o : trim-comments.c
        gcc -c -Wall -pedantic -ansi trim-comments.c -o trim-comments.o <test.c

test.c是包含用户代码的文件以及我要删除的一些注释。

0 个答案:

没有答案