FindFile function
Posted: Sun Nov 04, 2018 8:04 pm
				
				I needed a function that can find a file in a folder.
I made FindFile$(Dir$, Search$, Ext$, Upsort)
• Searches file in folder 'Dir$' which name contains 'Search$' and ends with 'Ext$'.
• Search is case-insensitive
• It returns the latest matching name from the sorted folder listing
• Upsort = 1 results in Ascending sort, Upsort = 0 in Descending
The following code includes the test program:
			I made FindFile$(Dir$, Search$, Ext$, Upsort)
• Searches file in folder 'Dir$' which name contains 'Search$' and ends with 'Ext$'.
• Search is case-insensitive
• It returns the latest matching name from the sorted folder listing
• Upsort = 1 results in Ascending sort, Upsort = 0 in Descending
The following code includes the test program:
Code: Select all
'Find file.sb by Dutchman, November 2018
'
'==== test variables
In$="Fractal" ' part of filename
Last$="txt" ' extension
Folder$="/Examples/Games" ' folder where to search
'==== Main
File$=FindFile$(Folder$,In$,Last$,1)
IF File$<>"" THEN
  PRINT "Found in ascending order: """&File$&"""." 
  File$=FindFile$(Folder$,In$,Last$,0)
  PRINT "Found in descending order: """&File$&"""." 
ELSE
  PRINT "No match found."
ENDIF
END
'=========== Function ===========
DEF FindFile$(Dir$,Search$,Ext$,Upsort) ' by Dutchman
'Search is case-insensitive
'Searches file in folder 'Dir$'
'   which name contains 'Search$'
'     and ends with 'Ext$'.
'It returns the latest matching name
'  from the sorted folder-listing
'Upsort=1 is Ascending, Upsort=0 is Descending
ob=OPTION_BASE()
Search$=LOWSTR$(Search$)
Ext$=LOWSTR$(REVERSE$(Ext$))'reverse search
IF Dir$="" THEN Dir$="."
File$=""
DIR Dir$ LIST FILES A$,n
OPTION SORT INSENSITIVE
IF Upsort THEN OPTION SORT ASCENDING ELSE OPTION SORT DESCENDING
SORT A$
FOR i=ob TO n-1+ob
  IF INSTR(LOWSTR$(a$(i)),Search$,ob)>=ob THEN
    IF Ext$<>"" THEN
      IF INSTR(LOWSTR$(REVERSE$(a$(i))),Ext$)=ob THEN File$=a$(i)
    ELSE ! File$=a$(i) ! ENDIF
  ENDIF
NEXT i
OPTION BASE ob
RETURN File$
END DEF