Search in file (taking into consideration of the comment delimiters)

From NSIS Wiki
Jump to navigationJump to search
Author: WarmAr (talk, contrib)


Description

Originally this function was written for search of ocurrences in a text file 'services' but can be useful in other cases.

Examples of Use

FileOpen $OpenFileHandle 'C:\WINNT\system32\drivers\etc\services' r
Push $OpenFileHandle
Push ''
Push 'gds_db'
Push 'begin'
Call SearchInFile
Pop $0 
StrCmp $0 yes lbl_SuccessfulSearch
 
; or
 
FileOpen $OpenFileHandle 'C:\WINNT\system32\drivers\etc\services' r
Push $OpenFileHandle
Push '#'
Push '3050/tcp'
Push 'anywhere'
Call SearchInFile
Pop $0 
StrCmp $0 yes lbl_SuccessfulSearch

The Function

Function SearchInFile
 
; HOW USE
; FileOpen $1 'C:\WINNT\system32\drivers\etc\services' r
; Push $handle  ; handle of file (open in 'a' or 'r' mode)
; Push '#'      ; comments delimiter (All symbols more to the right 
;               ; are ignored)
; Push 'gds_db' ; sample of search
;               ; push '' if comment_symbol are not defined
; Push 'no'     ; search mode. If 'begin' to search only from the 
;               ; beginning of string
; Call SearchInFile
; Pop $0        ; Result of search: yes/no 
;
 
Exch $3 ; search mode 
Exch 3 
Exch $2 ; file handle 
Exch 2 
Exch $1 ; comments delimiter 
Exch 
Exch $0 ; search sample
Exch 3
Exch
Exch 2
Exch
 
Push $4 ; string from file
Push $5	; length of string 
Push $6 ; not used
Push $7 ; search result
Push $8 ; not used
Push $9 ; not used
Push $R0 ;length of the search sample
Push $R1 ;length of the comment symbol
Push $R2 ;tmp
 
ClearErrors
StrLen $5 $0
StrCpy $7 no
 
StrLen $R0 $0
StrLen $R1 $1
 
lbl_SearchInFile_loop:
FileRead $2 $4
IfErrors lbl_SearchInFile_done
 
StrCmp $3 'begin' lbl_SearchFromBeginOnly lbl_SearchInString_loop
 
lbl_SearchFromBeginOnly:
StrLen $5 $4
StrCpy $R2 $4 $R0				                 
StrCmp $R2 $0 lbl_SampleIsFound lbl_SearchInFile_loop
 
lbl_SearchInString_loop:
StrCmp "" $4  lbl_SearchInFile_loop
StrLen $5 $4 
StrCmp "" $1  lbl_SearchSampleCont  ; search for the comments delimiter
StrCpy $R2 $4 $R1
StrCmp $R2 $1 lbl_SearchInFile_loop
 
lbl_SearchSampleCont:	
StrCpy $R2 $4 $R0	                  ; search as such the sample
StrCmp $R2 $0 lbl_SampleIsFound
IntOp $5 $5 - 1 	 ; cut a char at the left and continue search
StrCpy $4 $4 $5 1 
Goto lbl_SearchInString_loop
 
lbl_SampleIsFound:
StrCpy $7 yes
 
lbl_SearchInFile_done:
  StrCpy $0 $7
 
Pop $R2
Pop $R1
Pop $R0
Pop $9
Pop $8
Pop $7
Pop $6
Pop $5
Pop $4
Pop $3
Pop $2
Pop $1 
Exch $0 ;output yes/no
 
FunctionEnd