What is the fastest way to count lines and words in a text file in pure ANSI C?
A word is terminated by a space or period. Line is terminated by '\n'
.
What is the fastest way to count lines and words in a text file in pure ANSI C?
A word is terminated by a space or period. Line is terminated by '\n'
.
EOF
Maybe take a look at the source code of the GNU wc utility as this utility does exactly what you want.
Found at: http://www.gnu.org/software/cflow/manual/html_node/Source-of-wc-command.html
Here is an explicit answer that counts the number of lines (extension to the number of words is trivial à la the C++ version linked to in OP). This version is buffered. Another answer suggests reading the entire file in first, which is simpler, but the below is more in line with what your C++ example does.
The BUFSIZE macro can be tweaked to maximize performance (since you say you want the fastest way). 1024 is simply a guess. Another possibility is probably to read the file memory mapped, but I didn't try since mmap is not ANSI C.