FindIt: Simple search for file / directory

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


Description

A lot of new people found it hard to understand how to use the other file search functions, so I decided to post my version (which is a modified version of Kichik's). It doesn't require a callback function. It simply finds a file or directory, or it doesn't.

The only downside to using this function though is that if the file that you are locating does not have a unique name, then you could come up with another file or directory path instead!

Usage

${FindIt} "C:\look_in_here" "find_this.txt" "$R0"
; At this point; $R0 is path to "find_this.txt" or -1 (not found)

Note: Don't put a leading back-stroke (\) on end of "C:\look_in_here" path, else you will get a path like:

"C:\look_in_here\\find_this.txt"

The Function

!macro FindIt In For Result
Push "${In}"
Push "${For}"
 Call FindIt
Pop "${Result}"
!macroend
!define FindIt "!insertmacro FindIt"
 
Function FindIt
Exch $R0
Exch
Exch $R1
Push $R2
Push $R3
Push $R4
Push $R5
Push $R6
 
 StrCpy $R6 -1
 StrCpy $R3 1
 
 Push $R1
 
 nextDir:
  Pop $R1
  IntOp $R3 $R3 - 1
  ClearErrors
   FindFirst $R5 $R2 "$R1\*.*"
 
 nextFile:
  StrCmp $R2 "." gotoNextFile
  StrCmp $R2 ".." gotoNextFile
 
  StrCmp $R2 $R0 0 isDir
   StrCpy $R6 "$R1\$R2"
   loop:
    StrCmp $R3 0 done
     Pop $R1
     IntOp $R3 $R3 - 1
     Goto loop
 
 isDir:
 
  IfFileExists "$R1\$R2\*.*" 0 gotoNextFile
  IntOp $R3 $R3 + 1
  Push "$R1\$R2"
 
 gotoNextFile:
  FindNext $R5 $R2
  IfErrors 0 nextFile
 
 done:
  FindClose $R5
  StrCmp $R3 0 0 nextDir
  StrCpy $R0 $R6
 
Pop $R6
Pop $R5
Pop $R4
Pop $R3
Pop $R2
Pop $R1
Exch $R0
FunctionEnd

-Stu