Find a string in a file
Posted: Mon Aug 25, 2008 5:11 pm
Works also with PB 5.20
I hope the code (+ comments) is pretty self-explanatory. The file can be of arbitrary size.
Regards, Little John
edit:
There is another version in the third post.
I hope the code (+ comments) is pretty self-explanatory. The file can be of arbitrary size.
Regards, Little John
edit:
There is another version in the third post.
Code: Select all
; tested with PB 4.20
EnableExplicit
Procedure.q FindInFile (infile.s, search.s, start.q=0, matchCase.l=#True, maxChunk.l=4096)
; -- Look in <infile> for string <search>, beginning at offset <start>;
; works in ASCII mode and Unicode mode.
; Note: The first offset in the file is 0 (not 1)!
; out: * offset in the file, where <search> was found
; * -1: <search> was not found in <infile>
; * -2: <infile> couldn't be opened for reading
; * -3: the size of <search> is bigger than <maxChunk>
Protected buffer.s
Protected move.l, ifn.l, bytes.l, posn.q
move = maxChunk - StringByteLength(search) + 1
If move < 1
ProcedureReturn -3 ; error
EndIf
ifn = ReadFile(#PB_Any, infile)
If ifn = 0
ProcedureReturn -2 ; error
EndIf
If matchCase = #False
search = UCase(search)
EndIf
If SizeOf(Character) = 2 ; Unicode mode
buffer = Space(maxChunk/2+1)
Else
buffer = Space(maxChunk)
EndIf
Repeat
FileSeek(ifn, start)
bytes = ReadData(ifn, @buffer, maxChunk)
If matchCase = #False
buffer = UCase(buffer)
EndIf
posn = FindString(buffer, search, 1) - 1
If posn <> -1 ; found
If SizeOf(Character) = 2 ; Unicode mode
posn * 2
EndIf
posn + start
Break
EndIf
start + move
Until bytes < maxChunk
CloseFile(ifn)
ProcedureReturn posn
EndProcedure
;-- Demo
Define infile.s, search.s
infile = "source.txt"
search = "Hello World!"
Debug FindInFile(infile, search)