REM Word-count by simon laszcz
'
CLEAR
GOSUB getfile
WHILE file$<>""
GOSUB word_count
GOSUB output
GOSUB getfile
WEND
END
'
PROCEDURE getfile
LOCAL temp$
CLS
CLR file$
FILESELECT "A:\*.*"," ",temp$
IF EXIST(temp$)=-1 AND LEN(temp$)>3 THEN
LET file$=temp$
ENDIF
RETURN
'
PROCEDURE word_count
ON ERROR GOSUB declaratives
LOCAL line$,word!
CLR line$,sub%,words%
CLS
PRINT "Please wait. Reading file: ";file$
'
OPEN "i",#1,file$
LINE INPUT #1,line$
WHILE line$<>""
word!=FALSE
FOR sub%=1 TO LEN(line$)
IF ASC(MID$(line$,sub%,1))<>32 THEN
word!=TRUE
ELSE
IF word!=TRUE
INC words%
word!=FALSE
ENDIF
ENDIF
NEXT sub%
IF word!=TRUE
INC words%
ENDIF
CLR line$
LINE INPUT #1,line$
WEND
CLOSE #1
RETURN
'
PROCEDURE declaratives
RESUME NEXT
RETURN
'
PROCEDURE output
LOCAL button%
ALERT 1,"Words: "+STR$(words%),1,"OK",button%
RETURN
|
After clearing the memory the program asks the user to select a file and as long as one is chosen (i.e. the filename is not empty, file$<>"") the analysis is performed, the result output and the user asked to select another file. getfile displays a file selection box and accepts the filename into the local variable temp$. If a valid file is selected the contents of temp$ is assigned to file$, otherwise file$ is left empty (due to CLR file$) and will terminate the WHILE loop in the main program. word_count first declares the error handling sub-routine declaratives. declaratives will be executed after an error and asserts that program execution resume from the next command. In this case an error will occur when the program tries to read past the end of the file with the statement LINE INPUT #1,line$. Execution will then resume at the statement CLOSE #1. While the end of file is not met, the program uses the occurence of space to count the number of words on each line. The flag word! is first set to FALSE. The program then tests each character in turn, if it's anything but a space word! is set to TRUE. If it's a space words% is incremented, but only if word!=TRUE. This ensures that leading spaces are ignorred. At the end of the line words% is incremented if the last character to be tested was not a space. The result of the word count is output using an alert box in the output sub-routine. button% is a dummy variable used to store the number of the button pressed (i.e. 1). |