TA: Francis Hsu
Email: fahsu@ucdavis.edu
Website: http://wwwcsif.cs.ucdavis.edu/~hsuf/ecs40
Office Hours: 53 Kemper Tu 3:30-5:30, Th 10-12
1: #include <stdio.h>
2:
3: #define SUCCESS 1
4: #define FAILURE 0
5:
6: #define MAX_WORDS 100000
7: #define MAX_LENGTH 1024
8:
9:
10: /* words.c: print some statistics about the words in a
11: file of words with one word per line */
12:
13: typedef struct word_struct{
14: char letters[MAX_LENGTH];
15: int length;
16: } word;
17:
18: word* words[MAX_WORDS];
19: int num_words = 0;
20:
21: void show_help(void) {
22: printf("Usage: words [-w|-c] filename\n");
23: exit(1);
24: }
25:
26: void chomp(char* line) {
27: while(*line != 0) {
28: if (*line == '\n') {
29: *line = 0;
30: return;
31: }
32: line++;
33: }
34: }
35:
36: int read_file(char* filename) {
37: FILE *file_handle;
38: char* char_buf;
39: word* cur_word;
40:
41: file_handle = fopen(filename, "r");
42: if (file_handle == NULL) {
43: return FAILURE;
44: }
45:
46: char_buf = (char*) malloc(MAX_LENGTH * sizeof(char));
47: if (char_buf == NULL) {
48: return FAILURE;
49: }
50:
51: do {
52: if (!fgets(char_buf, MAX_LENGTH, file_handle)) {
53: break;
54: }
55: chomp(char_buf);
56: cur_word = (word*) malloc(sizeof(word));
57: if (cur_word == NULL) {
58: return FAILURE;
59: }
60: strncpy(cur_word->letters, char_buf, MAX_LENGTH);
61: cur_word->length = strlen(cur_word->letters);
62: words[num_words] = cur_word;
63: num_words++;
64: } while (1);
65:
66: return SUCCESS;
67: }
68:
69: void count_words() {
70: printf("%d\n", num_words);
71: }
72:
73: void count_chars() {
74: int i;
75: int count = 0;
76: for (i=0; i<num_words; i++) {
77: count += words[i]->length;
78: }
79: printf("%d\n", count);
80: }
81:
82: int main (int argc, char* argv[]) {
83: if (argc == 3) {
84: if (read_file(argv[2]) == FAILURE) {
85: exit(1);
86: }
87: if (strncmp(argv[1], "-w", 3) == 0) {
88: count_words();
89: exit(0);
90: }
91: if (strncmp(argv[1], "-c", 3) == 0) {
92: count_chars();
93: exit(0);
94: }
95: }
96: show_help();
97: }