본문 바로가기
대학교/4.컴파일러

[01] wc

by Jcoder 2019. 3. 20.


main.c

Makefile

wc.c



main.c

#include <stdio.h>
#include <stdlib.h>
extern void countfile(), printtotal();
main(int argc, char *argv[])
{
register FILE *fp;
register int i;
if (argc == 1)
countfile(stdin, "");
else {
i = 1;
while (i < argc) {
if ((fp = fopen(argv[i], "r")) == NULL)
fprintf(stderr, "%s: %sA≫(¸|) ¿­ ¼o ¾ø½A´I´U\n", argv[0], argv[i]);
else {
countfile(fp, argv[i]);
fclose(fp);
}
i++;
}
if (argc > 2) printtotal();
}
exit(0);
}

wc.c

#include <stdio.h>
#define BufSize 16
#define Sentinel '\0'
static unsigned char buf[BufSize*2+1];
static unsigned char *lexeme_beginning, *forward;
#define NextChar() ((*forward)? *forward++:((forward=buf+BufSize+1),fillbuf(fp)))
static int wl = 0, ww = 0, wc =0; // Line, Word, Char Count
static int whiteChars[256] = {
0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
};
#define IsWhite(c) (whiteChars[c])
static unsigned char fillbuf(FILE *fp)
{
register unsigned char *i, *j;
/* move the rest of token to the other buffer */
i = lexeme_beginning;
j = lexeme_beginning - BufSize;
while (j <= forward)
*(j++) = *(i++) ;
lexeme_beginning -= BufSize;
buf[BufSize + fread(buf+BufSize, 1, BufSize, fp)] = Sentinel;
return buf[BufSize];
}
void countfile(FILE *fp, char *fname)
{
int flag = 0; // Word flag
int fc = 0, fl = 0, fw = 0; // each file count
unsigned char ch;
buf[BufSize*2] = Sentinel;
forward = buf + BufSize*2;
lexeme_beginning = buf + BufSize;
/* FILL IN THIS BLANK */
while(ch = NextChar())
{
++fc; // Char count++
if(ch == '\n')
fl++; // Line Count++
if(IsWhite(ch))
{
lexeme_beginning = forward;
flag = 0;
}
else if (flag == 0)
{
flag = 1;
++fw; // Word Count++
}
}
wl += fl; ww += fw; wc += fc; // add
printf("Line || Word || Char || File\n----------------------------\n%4d || %4d || %4d || %s\n============================\n", fl, fw, fc, fname);
}
void printtotal()
{
/* FILL IN THIS BLANK */
printf("Line || Word || Char ||\n-----------------------\n%4d || %4d || %4d || 합계\n============================\n", wl, ww, wc);
}

Makefile


wc: main.o wc.o
cc -o wc main.o wc.o
main.o: main.c
cc -c main.c
wc.o: wc.c
cc -c wc.c
clean:
rm -f *.o


'대학교 > 4.컴파일러' 카테고리의 다른 글

[03] lex.l  (0) 2019.04.14
[02] lex.c  (0) 2019.04.14