|
|
Program development begins with the creation of code from specifications. Sometimes, the code has already been written and must only be tested and debugged. This tutorial includes a sample program.
The sample program, testcase.c, was written to these specifications:
The file testcase.c contains the following code:
1 #include <stdio.h>
2 #include <ctype.h>
3 #include <string.h>
4
5 /* Manifests for state machine to parse input line. */
6 #define WORD 0
7 #define IGNORE 1
8
9 #define BUFFERSIZE 5000
10
11 /* Globals, used by both subroutines. */
12 char *Words[BUFSIZ/2]; /* Worst case, single letters. */
13 int WordCount;
14
15 /* Walk through the array of words, find those with the
16 * matching character, printing them on stdout. Note that
17 * the null character will match all words. */
18 void PrintWords(wc, match)
19 int wc; /* Number of words in Words[] */
20 char match; /* Attempt to match this character. */
21 { register int ix; /* Index in Words[]. */
22 register char *cp; /* Pointer for searching. */
23 for(ix = 0; ix < wc; ix++) {
24 cp = Words[ix];
25 /* Try to match the given character.
26 * Scan the word, attempting to match,
27 * or until the end of the word is found. */
28 while((*cp) && (*cp++ != match));
29 if (*cp == match) /* Found a match? Write the word on stdout. */
30 (void) printf("%s\n", Words[ix]); } return; }
31
32 /* Find words in the given buffer. The Words[] array is set
33 * to point at words in the buffer, and the buffer modified
34 * with NULL characters to delimit the words. */
35 int GetWords(buf)
36 char buf[]; /* The input buffer. */
37 { register char *cp; /* Pointer for scanning. */
38 int end = strlen(buf); /* Length of the buffer. */
39 register int wc = 0; /* Number of words found. */
40 int state = IGNORE; /* Current state. */
41 /* For each character in the buffer. */
42 for(cp = &buf[0]; cp < &buf[end]; cp++) {
43 /* A simple state machine to process
44 * the current character in the buffer.
45 */
46 switch(state) {
47 case IGNORE:
48 if (!isspace(*cp)) {
49 Words[wc++] = cp; /* Just started a word?
50 Save it. */
51 state = WORD; /* Reset the state. */ } break;
52 case WORD:
53 if (isspace(*cp)) {
54 *cp = '\0'; /* Just completed a word?
55 terminate it. */
56 state = IGNORE; /* Reset the state. */ } break; } }
57 return wc; /* Return the word count. */ }
58
59 int main(argc, argv) int argc; char *argv[]; { char buf[BUFSIZ], match;
60 /* Check command line arguments. */
61 if (argc < 2) match = ' ';
62 /* No command line argument, match all words. */
63 else match = *++argv[1]; /* Match the char after the first - */
64 /* Until no more input on stdin. */
65 while(gets(buf) != (char *)NULL) {
66 WordCount = GetWords(buf); /* Parse the input buffer. */
67 PrintWords(WordCount, match); /* Print the matching words. */ }
68 return(0); /* Return success to the shell. */ }