-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathch2-03.l
70 lines (57 loc) · 1.35 KB
/
ch2-03.l
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
%{
#undef yywrap
unsigned long charCount = 0, wordCount = 0, lineCount = 0;
char **fileList;
unsigned currentFile;
unsigned nFiles;
unsigned long totalCC = 0, totalWC = 0, totalLC = 0;
%}
word [^ \t\n]+
eol \n
%%
{word} { wordCount++; charCount += yyleng; }
{eol} { charCount++; lineCount++; }
. { charCount++; }
%%
void attachFile(unsigned *pIndex)
{
/* printf("*pIndex %u, nFiles %d\n", *pIndex, nFiles); */
FILE *file;
if (!yyin) {
fclose(yyin); /* close previous file if there is any */
}
file = fopen(fileList[*pIndex], "r");
if (!file) {
fprintf(stderr, "could not open %s\n", fileList[*pIndex]);
exit(1);
}
yyin = file;
(*pIndex)++;
/* printf("*pIndex %u, nFiles %d\n", *pIndex, nFiles); */
}
int main(int argc, char **argv)
{
fileList = argv + 1;
nFiles = argc - 1;
currentFile = 0;
attachFile(¤tFile); /* exit here if nFiles == 0 */
yylex();
return 0;
}
int yywrap()
{
printf("%8lu %8lu %8lu %s\n", lineCount, wordCount, charCount, fileList[currentFile-1]);
totalLC += lineCount;
totalWC += wordCount;
totalCC += charCount;
charCount = wordCount = lineCount = 0;
if (currentFile >= nFiles) {
if (nFiles > 1) {
printf("%8lu %8lu %8lu total\n", totalLC, totalWC, totalCC);
}
return 1; /* end lexing */
} else {
attachFile(¤tFile);
return 0; /* more input */
}
}