Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

ONLY C LANGUAGE For your first project I want you to write a concordance program

ID: 3562717 • Letter: O

Question

ONLY C LANGUAGE

For your first project I want you to write a concordance program: a program
to count the number of occurrences of words in a passage. The program will
read white-space separated words from a file, convert all words to a single
case, and remove any non-alphanumeric characters from both ends of the
words. It is to count the number of each word, and then write to a file a list
of word/count pairs, sorted by word.
The program will take 2 command-line arguments: a filename for the input
and a filename for the output. The same character classification functions
and character case-conversion functions are available as in C++; you will
have to include the system header

Explanation / Answer

#include <stdio.h>
#include <string.h>

#define MAX_LINE_LEN 1024
#define WS " ",:;(){}[]<>/\=+ "
#define END ".?!"

int main(int argc, char *argv[]) {
FILE *fp;
char line[MAX_LINE_LEN],*s;
int numWords = 0,
totalWordLen = 0,
numSentences = 0;

if ((argc < 2) ||
((fp = fopen(argv[1],"r")) == NULL)) {
printf(" usage : %s <filename> ",argv[0]);
return -1;
}
while (fgets(line,MAX_LINE_LEN,fp) != NULL) {
*strchr(line,' ') = '';
for (s = strtok(line,WS); s != NULL; s = strtok(NULL,WS)) {
++numWords;
totalWordLen += (strchr(s,'') - s);
if (strpbrk(s,END) != NULL) {
++numSentences;
--totalWordLen;
}
}
}
printf(" word count : %d",numWords);
if (numWords > 0) {
printf(" avg word len = %g",
(float)totalWordLen / (float)numWords);
}
printf(" sentence count : %d",numSentences);
if (numSentences > 0) {
printf(" avg sentence length = %g words",
(float)numWords / (float)numSentences);
}
puts("");
fclose(fp);
return 0;
}


Sample run:

$ ./myWc dp.txt

word count : 63
avg word len = 3.92063
sentence count : 5
avg sentence length = 12.6 words


Checking:

$ wc dp.txt
5 63 323 dp.txt