Jump to content

Recursive file/folder search - training exercise


Recommended Posts

I am new to the world of AutoIT and trying to get up to speed.  I am currently stuck on this exercise.

Recursive File Search:
 
Allow the user to specify a folder location to search for all files or folders
that contain a set of characters that they specify. Develop an easy-to-use way for the user to 
specify more than once search criteria, and also more than one search folder, and an effective method for outputting the results.
 
I have written the following which will return the contents of the initial folder and contents of the folders inside that folder but I am not sure how to proceed.
 
At some point in no longer returned the folder names in the array it creates, not sure where I went wrong.
 
Any help would be appreciated.
#NoTrayIcon
#include <Array.au3>

Global $aSearch1[1], $i, $found

$SearchFold = InputBox("", "Input the folder you want to search","C:\blablabla")
$SearchString = InputBox("", "Input value you want to search for", "*.*")
;~ $SearchString = "*" & $SearchString & "*"

_FileSearch( $SearchFold, $SearchString )

_ArrayDisplay( $aSearch1, "Search Results" )

$i = 0

Func _FileSearch( $startfold, $searchval )   ; declares function

FileChangeDir($startfold)      ; changes the working directory,  directory is being searched
    
$search = FileFindFirstFile( $searchval ) 

If $search = -1 Then                       ; Check if the search was successful
    MsgBox(0, "Error", "No files/directories matched the search pattern")
    Exit
EndIf

While 1
    $file = FileFindNextFile( $search ) 
    If @error Then ExitLoop
    $found = $startfold & "\" & $file   

    $dirchk = StringInStr(FileGetAttrib($found), "D" ) ;directory check
        Select
            Case  $dirchk > 0
                _FileSearch( $found, $searchval ) ;recurse if directory found
            Case $dirchk = 0
                $found = $startfold & "\" & $file   ;return $found if not a directory
        EndSelect

    $aSearch1[$i] = $found  ;write found to the array
    $i = $i + 1               ;increase the value of $i
    ReDim $aSearch1[$i +1]    ;redim the array
WEnd

ReDim $aSearch1[UBound( $aSearch1 ) -1]  ;trim the array

$i = UBound($aSearch1) -1

FileClose($search)   ; Close the search handle
EndFunc
 
 
Link to comment
Share on other sites

  • Moderators

I would personally check out Melba's RecFileListToArray, read all the files and folders into the array, and then present only those that match your query value.

http://www.autoitscript.com/forum/index.php?showtopic=126198

"Profanity is the last vestige of the feeble mind. For the man who cannot express himself forcibly through intellect must do so through shock and awe" - Spencer W. Kimball

How to get your question answered on this forum!

Link to comment
Share on other sites

I'm a big fan of _FilelistToArray.  Here's is how I have used it recursively.

#include <File.au3>

$outputfile = "output.txt"
$rootdir = @ScriptDir
FileOpen($outputfile,2)
_SearchFolder($rootdir)
FileClose($outputfile)

Func _SearchFolder($folder,$filter="*")
    $files = _FileListToArray($folder,$filter,1)
    $folders = _FileListToArray($folder,$filter,2)
    _FileFunc($files,$folder)
    _FolderFunc($folders,$folder)
EndFunc

Func _FileFunc($files,$folder)
    For $i = 1 To UBound($files)-1
        FileWrite($outputfile, $folder & "\" & $files[$i] & @CRLF)
    Next
EndFunc

Func _FolderFunc($folders,$parentdir)
    For $i = 1 To UBound($folders)-1
        _SearchFolder($parentdir & "\" & $folders[$i])
    Next    
EndFunc

Melba's UDF is also very good and well written.

Just wanted to give you another example.  I agree that exercises can be fun and useful, but sometimes reinventing the wheel isn't worth the time and effort.

Link to comment
Share on other sites

Thanks for the help/input everyone, although I understand reinventing the wheel isn't usually worth it, in this case it has helped me to gain a better understanding of autoit, which was what was intended when I was assigned this training exercise.

Link to comment
Share on other sites

...in this case it has helped me to gain a better understanding of autoit, which was what was intended when I was assigned this training exercise.

Well done

Link to comment
Share on other sites

Learning is great! It's when people say things such as "I don't like using other peoples UDFs, so I want to create my own" is when you're re-inventing the wheel.

UDF List:

 
_AdapterConnections()_AlwaysRun()_AppMon()_AppMonEx()_ArrayFilter/_ArrayReduce_BinaryBin()_CheckMsgBox()_CmdLineRaw()_ContextMenu()_ConvertLHWebColor()/_ConvertSHWebColor()_DesktopDimensions()_DisplayPassword()_DotNet_Load()/_DotNet_Unload()_Fibonacci()_FileCompare()_FileCompareContents()_FileNameByHandle()_FilePrefix/SRE()_FindInFile()_GetBackgroundColor()/_SetBackgroundColor()_GetConrolID()_GetCtrlClass()_GetDirectoryFormat()_GetDriveMediaType()_GetFilename()/_GetFilenameExt()_GetHardwareID()_GetIP()_GetIP_Country()_GetOSLanguage()_GetSavedSource()_GetStringSize()_GetSystemPaths()_GetURLImage()_GIFImage()_GoogleWeather()_GUICtrlCreateGroup()_GUICtrlListBox_CreateArray()_GUICtrlListView_CreateArray()_GUICtrlListView_SaveCSV()_GUICtrlListView_SaveHTML()_GUICtrlListView_SaveTxt()_GUICtrlListView_SaveXML()_GUICtrlMenu_Recent()_GUICtrlMenu_SetItemImage()_GUICtrlTreeView_CreateArray()_GUIDisable()_GUIImageList_SetIconFromHandle()_GUIRegisterMsg()_GUISetIcon()_Icon_Clear()/_Icon_Set()_IdleTime()_InetGet()_InetGetGUI()_InetGetProgress()_IPDetails()_IsFileOlder()_IsGUID()_IsHex()_IsPalindrome()_IsRegKey()_IsStringRegExp()_IsSystemDrive()_IsUPX()_IsValidType()_IsWebColor()_Language()_Log()_MicrosoftInternetConnectivity()_MSDNDataType()_PathFull/GetRelative/Split()_PathSplitEx()_PrintFromArray()_ProgressSetMarquee()_ReDim()_RockPaperScissors()/_RockPaperScissorsLizardSpock()_ScrollingCredits_SelfDelete()_SelfRename()_SelfUpdate()_SendTo()_ShellAll()_ShellFile()_ShellFolder()_SingletonHWID()_SingletonPID()_Startup()_StringCompact()_StringIsValid()_StringRegExpMetaCharacters()_StringReplaceWholeWord()_StringStripChars()_Temperature()_TrialPeriod()_UKToUSDate()/_USToUKDate()_WinAPI_Create_CTL_CODE()_WinAPI_CreateGUID()_WMIDateStringToDate()/_DateToWMIDateString()Au3 script parsingAutoIt SearchAutoIt3 PortableAutoIt3WrapperToPragmaAutoItWinGetTitle()/AutoItWinSetTitle()CodingDirToHTML5FileInstallrFileReadLastChars()GeoIP databaseGUI - Only Close ButtonGUI ExamplesGUICtrlDeleteImage()GUICtrlGetBkColor()GUICtrlGetStyle()GUIEventsGUIGetBkColor()Int_Parse() & Int_TryParse()IsISBN()LockFile()Mapping CtrlIDsOOP in AutoItParseHeadersToSciTE()PasswordValidPasteBinPosts Per DayPreExpandProtect GlobalsQueue()Resource UpdateResourcesExSciTE JumpSettings INISHELLHOOKShunting-YardSignature CreatorStack()Stopwatch()StringAddLF()/StringStripLF()StringEOLToCRLF()VSCROLLWM_COPYDATAMore Examples...

Updated: 22/04/2018

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...