9p / who / tweedy / 9C / 1


Exercise 1.23: Decomment

Code

#include <u.h>
#include <libc.h>
#include <bio.h>

#define STDIN   0
#define MAXLINE 1000
#define BEGIN   0
#define END 1
#define OUT 2

/* removes all comments from a C program (ignores // style) */
void
main()
{
    Biobuf *bstdin;         /* test comment */
    bstdin = Bfdopen(STDIN, OREAD);
    int state;
    char c, prev;

    prev = Bgetc(bstdin);
    state = OUT;
    while((c = Bgetc(bstdin)) >= 0){
        if(prev=='/' && c=='*')
            state = BEGIN;
        else if(prev=='*' && c=='/')
            state = END;
        if(state == BEGIN)
            ;
        else if(state == END){
            c = Bgetc(bstdin);
            state = OUT;
            }
        else if(state == OUT){
            print("%c", prev);
        }
        prev = c;
    }

exits(0);
}

/* let's test some multi-line comments too
int getline(Biobuf *b, char s[], int lim)
{
    int c, i;

    for(i = 0; i<lim-1 && (c=Bgetc(b))>= 0 && c!='\n'; ++i)
        s[i] = c;
    if(c == '\n'){
        s[i] = c;
        ++i;
    }
    s[i] = '\0';
    return i;
}
*/

Output

$ 9c decomment.c; 9l decomment.o -o decomment
$ ./decomment < decomment.c
#include <u.h>
#include <libc.h>
#include <bio.h>

#define STDIN   0
#define MAXLINE 1000
#define BEGIN   0
#define END 1
#define OUT 2


void
main()
{
    Biobuf *bstdin;         
    bstdin = Bfdopen(STDIN, OREAD);
    int state;
    char c, prev;

    prev = Bgetc(bstdin);
    state = OUT;
    while((c = Bgetc(bstdin)) >= 0){
        if(prev=='/' && c=='*')
            state = BEGIN;
        else if(prev=='*' && c=='/')
            state = END;
        if(state == BEGIN)
            ;
        else if(state == END){
            c = Bgetc(bstdin);
            state = OUT;
            }
        else if(state == OUT){
            print("%c", prev);
        }
        prev = c;
    }

exits(0);
}





tweedy