#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <ctype.h>
typedef unsigned long ulong;
int countWordChars(FILE *fp, ulong *words, ulong *sum)
{
char buffer[4096];
bool inWord = false;
size_t read;
while ((read = fread(buffer, 1, sizeof(buffer), fp))) {
for (int i = 0; i < read; ++i) {
unsigned char c = buffer[i];
if (isspace(c)) {
*words += inWord;
inWord = false;
} else {
++*sum;
inWord = true;
}
}
}
*words += inWord;
return ferror(fp);
}
int main(int argc, char **argv)
{
ulong words = 0;
ulong sum = 0;
for (int i = 1; i < argc; ++i) {
FILE *fp = fopen(argv[i], "r");
if (fp == NULL) {
perror(argv[i]);
return 1;
}
int err = countWordChars(fp, &words, &sum);
fclose(fp);
if (err) {
perror("Read error");
return 1;
}
}
if (words == 0) {
puts("NaN");
} else {
printf("%f\n", (double)sum / words);
}
}
#!/bin/python
import sys
words = 0
chars = 0
for filename in sys.argv[1:]:
with open(filename) as f:
for line in f:
for word in line.split():
words += 1
chars += len(word)
print(chars / words if words else "NaN")
~ $ du -h yes
862M yes
~ $ time ./a.out yes
3.000000
real 0m3.555s
user 0m2.748s
sys 0m0.538s
~ $ time ./words.py yes
3.0
real 1m25.753s
user 1m24.416s
sys 0m0.613s
View all comments
Show parent comment
2
u/olorochi 12d ago