NASutils Knowledge BaseUnofficialPolski

BASIC · lesson 24 of 30 · Files and errorsCount words in a file

Read a file line by line and keep three sums.

Programming on the NAS › BASIC in 30 lessons

24-word-count.yab Download 24-word-count.yab

rem Counts lines, words and characters of a file
dim word$(1)
open #1, peek$("argument"), "r"
while not eof(1)
  line input #1 line$
  lines = lines + 1
  words = words + token(line$, word$(), " ")
  chars = chars + len(line$)
wend
close #1
print lines, " lines, ", words, " words, ", chars, " characters"

Terminal

$ yabasic 24-word-count.yab words.txt
3 lines, 18 words, 84 characters

Exercise

Count the empty lines as well.