/* counts the number of times a str shows up in a file */
define stream stSrc.
function searchStr returns int
( pcFile as char, pcStr as char ):
define var iLength as int no-undo.
define var iCnt as int no-undo.
assign
iLength = length( pcStr )
iCnt = 0.
define var rBuffer as raw no-undo.
define var cBuffer as char no-undo.
define var cTrail as char no-undo.
assign
length( rBuffer ) = 1024
cBuffer = ""
cTrail = "".
input stream stSrc from value( pcFile )
binary no-convert. /* codepage conv can be very costly with large files, up to you */
repeat:
/* read file in increments of 1k */
import stream stSrc unformatted rBuffer.
cBuffer = cTrail + get-string ( rBuffer, 1 ).
/* search thru the buffer */
define var iCursor as int no-undo.
define var iLast as int no-undo.
assign
iCursor = 1
iLast = iCursor.
repeat:
if length( cBuffer ) - iCursor + 1 < iLength then leave. /* length doesn't fit in space left */
iCursor = index( cBuffer, pcStr, iCursor ).
if iCursor = 0 then leave.
assign
iCursor = iCursor + iLength
iLast = iCursor
iCnt = iCnt + 1.
end. /* repeat */
/* there could be cases where the search str falls between buffers
* so a trail is carried on to the next buffer */
if iCursor <= length( cBuffer ) then
cTrail = substr( cBuffer, max( iLast,
length( cBuffer ) - ( iLength - 1 ) + 1 ) ).
end. /* repeat */
input stream stSrc close.
return iCnt.
end function. /* searchStr */