by tptacek · 6y ago · 0 comments
https://gist.github.com/tqbf/4de61a3e34d2e4664044666c107abe7...
(I don't vouch for this code; I wrote it off the top of my head, and, in keeping with the exercise, I wrote it in pico).
It's not 10x longer. I'm honestly not sure why either Rust or C++ bothered with regexps for this problem.
Anyways, you get the gist of what this looks like in C now. Obviously, don't write things like this in C.
With that fixed, this dumb program does my whole (very large) homedir in about 10 seconds, for some definition of "does" that may or may not include counting every word in every txt file. For the curious:
0. get / 566006
1. the / 158168
2. pkg / 119419
3. syscall / 105828
4. const / 98259
5. and / 86670
6. ideal-int / 43078
7. that / 31609
8. for / 31129
9. this / 24980
10. text / 22907
:P while (fgets(buf, 1024, fp)) {
char *c, word[1024], *w = word;
for (c = buf; *c; c++) {
*c = tolower(*c);
if (*c >= 'a' && *c <= 'z')
*w++ = *c;
else {
*w = '\0';
count(word, (size_t)(w - word));
w = word;
}
}
*w = '\0';
count(word, (size_t)(w - word));
}
and you have that `count` function skip words with len < 2 then I can match results with the other 3 (Nim, Rust, C++) versions. Also, your C version runs in just 7 ms on Tale Of Two Cities, about half the time of the PGO optimized Nim.This C code is not only not protecting you against that, but also it seems to have little to none error checking. What happens if fopen fails? It just skips to the next file and happily ignores all the entries in the file. What if fget fails? Again, it stops processing the file and goes to the next.
I won't even get into what happens if calloc fails and returns null. Or if ++ wraps around and you get a negative value (let's hope we are using 64 bits)
This program will likely work, but if it doesn't you will just get an invalid number and never find out.
Don't get me wrong, I understand this is "not serious" code, written in a Sunday and for fun. And I would be ok with it if the article wasn't about language safety.