Wednesday, March 12, 2008

letter counts per paragraph

Count up the number of each letter by paragraph.
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <strings.h>

int main(int numArgs, char** args)
{
const int lineSize = 10000;

if (numArgs != 2) {
fprintf(stderr, "Usage: par_char_freq <text file>\n");
exit(1);
}
else {
char* line = malloc(lineSize);
FILE* in = fopen(args[1], "r");
int counts[26];
int paragraphTotal = 0;

if (!in) {
fprintf(stderr, "Problem opening %s\n", args[1]);
perror("");
exit(1);
}

bzero(counts, 26 * sizeof(int));

while (!feof(in) && !ferror(in)) {
int lineTotal = 0;
if (fgets(line, lineSize, in)) {
int i;
for (i = 0; line[i]; ++i) {
const char c = tolower(line[i]);
if ('a' <= c && c <= 'z') {
++counts[c - 'a'];
++lineTotal;
}
}

if (lineTotal) {
paragraphTotal += lineTotal;
}
else if (paragraphTotal) {
int i;
for (i = 0; i < 26; ++i) {
printf("%d ", counts[i]);
}
printf("\n");

paragraphTotal = 0;
bzero(counts, 26 * sizeof(int));
}
}
}

fclose(in);
free(line);
}
return 0;
}

No comments: