AmarokStudios

Include Full Directory

1 post in this topic

Good afternoon AutoIt community!,

I was on Stackoverflow the other day and came across this question: How To Include Files From A Directory. This got me thinking... There has to be a way to do it... After a bunch of research, I wasn't able to find anything. So, I created this UDF to dynamically include every file from the directory. Of course, there are some bugs that I'd like to fix eventually, but for the most part, it works. Simply call the main function (Shown below) right after the rest of the includes before any of your actual code, and the UDF will include all of the au3 files in the specified directory. Without further ado, here is the _includeDir UDF and how to use it!

 

_includeDir.au3

Spoiler
#cs
        Name: _includeDir.au3
        Developer: Timothy Bomer
        Copyright: Amarok Studios LLC 2016
        Version: 1.0
        Description:
            The purpose of this UDF is to dynamically include all files inside of a folder.
            It works for the most part, but I am still working on a couple of bugs.
#CE


#Include <File.au3>


Global $mainUDF = "IncludeDirUDF"
Global $includeLib = $mainUDF & "\" & "loadIncludes.au3"
Global $tempLib = $mainUDF & "\" & "lib.txt"
Global $includeRewrite = $mainUDF & "\rewrite.au3"
Global $iDirHolder = ""


Func _includeDir($iDir, $lineToInc = 1, $restart = True)
    If (checkInclude()) = 1 Then
        FileDelete($tempLib)
        return
    EndIf
    If NOT (FileExists($iDir)) Then
        MsgBox(16,"Directory Doesn't Exists | _includeDir","The directory " & $iDir & " does not exist!")
        return 0
    EndIf
    $iDirHolder = $iDir
    initializeCheck()
    ; MsgBox(0,"Include Directory", "Attempting to include: " & $iDir)
    populateLib($iDir)
    populateIncLib()
    finalize($lineToInc, $restart)
EndFunc

Func checkInclude()
    FileOpen(@ScriptName, 0)
    For $i = 1 to _FileCountLines(@ScriptName)
        $checkLine = FileReadLine(@ScriptName, $i)
        If ($checkLine = '#Include "IncludeDirUDF\loadIncludes.au3"') Then
        return 1
        EndIf
    Next
EndFunc

; START Initialize Check
Func initializeCheck()
    ; MsgBox(0,"Checking. . .", "Is this initialized?")
    If (FileExists($mainUDF)) Then
        If NOT (FileExists($includeLib)) Then
            isError(2)
            return
        EndIf

        ; MsgBox(0,"Initialized","The UDF has been initialized")
    Else
        isError(1)
        return
    EndIf
EndFunc
; END Initialize Check

; START Library Population
Func populateLib($iDir = $iDirHolder)
    ; MsgBox(0,"Populating","Attempting to populate the library")
    If (FileExists($tempLib)) Then
        ; MsgBox(0,"Temp File Found","The temporary library file has been found. Attempting to populate.")
        $tLibCont = _FileListToArray(@ScriptDir & "\" & $iDir & "\", "*")
        $iDirSize = $tLibCont[0]
        ; MsgBox(0,"Size of Included Directory", $iDir & " contains " & $iDirSize & " files to include!")
        $writeLib = FileOpen($tempLib, 1)
        While $iDirSize > 0
            FileWriteLine($writeLib, '#Include "..\' & $iDir & '\' & $tLibCont[$iDirSize] & '"')
            $iDirSize -= 1
        WEnd
        FileClose($writeLib)
    Else
        isError(3)
        return
    EndIf
EndFunc
; END Library Population

; START Include Library Population
Func populateIncLib()
    ; MsgBox(0,"Rewriting. . .", "Attempting to re-write the include library")
    #CS
    If (FileExists($includeLib)) Then
        FileDelete($includeLib)
        _FileCreate($includeLib)
    EndIf
    #CE
    FileOpen($tempLib, 0)
    For $i = 1 to _FileCountLines($tempLib)
        $line = FileReadLine($tempLib, $i)
        $reWriteLib = FileOpen($includeLib, 9)
        FileWriteLine($reWriteLib, $line)
        FileClose($reWriteLib)
    Next
    FileClose($tempLib)
EndFunc
; END Include Library Population

; START Finalize
Func finalize($lineToInc, $restart)
    _FileWriteToLine(@ScriptName, $lineToInc, '#Include "IncludeDirUDF\loadIncludes.au3"', False)
    If ($restart = True) Then
        runFile(@ScriptName)
    EndIf
    exit
    return
EndFunc


Func runFile($rFile)
    $file_loc = $rFile

    If @Compiled = 1 Then
         $file_exe = FileGetShortName(@AutoItExe & ' /AutoIt3ExecuteScript "' & $file_loc & '"')
         Run($file_exe)
    Else
         $file_au3 = FileGetShortName($file_loc)
         Run(@AutoItExe & " " & $file_au3, "", @SW_HIDE)
     EndIf
EndFunc

; START Error Reporting
Func isError($eFlag = "", $eMessage = "There was an error!")
    If ($eFlag = "") Then
        ; MsgBox(16,"ERROR", $eMessage)
        Exit
    EndIf

    If ($eFlag = 1) Then
        ; MsgBox(16,"Not Initialized","This UDF has not been initialized")
        DirCreate($mainUDF)
        Sleep(250)
        initializeCheck()
        return
    ElseIf ($eFlag = 2) Then
        ; MsgBox(16,"Missing File","Missing the include library!")
        _FileCreate($includeLib)
        initializeCheck()
        return

    ElseIf ($eFlag = 3) Then
        ; MsgBox(16,"Missing File", "Missing the temporary library! Creating it now!",3)
        _FileCreate($tempLib)
        populateLib()
        return
    EndIf
EndFunc
; END Error Reporting

 

 

Download this code (_includeDir.au3 attached as well) and place it into the directory with your current script. Next, include it in your main file. For now, I'm going to be using one called Example.au3.

 

#Include "_includeDir.au3"

Now, include whatever else you're going to be including in this script, then call the _includeDir function. NOTE: THIS MUST BE CALLED AT THE TOP OF THE SCRIPT, BEFORE ANY CODE IS WRITTEN! THE FUNCTION FORCES THE SCRIPT TO RESTART SO PUTTING IT LATER IN THE SCRIPT WILL RE-RUN THE CODE!

 

Example.au3

#Include "_includeDir.au3"
#Include <File.au3> ; Not needed. Just here as an example of a normal script.
#Include <Array.au3> ; Not needed. Just here as example of normal script.
_includeDir("Directory to Include")

MsgBox(0,"Example","This is just an example!")

See how the function is called near the top? This is the proper use of the UDF. If you had a folder called "Directory to Include" and had a bunch of .au3 files inside of it, the function would include them all into the Example.au3 script.

If you run the Example.au3 file now, it will most likely tell you "The directory Things to Include does not exist!". Make sure you enter the name of the directory you're trying to include. Just as a side note, when including files, you should put all of the code in the INCLUDED files inside of functions so they aren't automatically run when included. Variables can be outside of the functions so they are automatically set. Remember, if you have a variable in one included file with the same name of variable in another included file, it will be overwritten with whichever include file was included last.

 

Anyways, if you have pointed the directory to include parameter to a folder that exists and run the Example.au3, it will generate a folder called IncludeDirUDF. It will also write a new line inside of Example.au3. It will write the line 

Quote

#Include "IncludeDirUDF\loadIncludes.au3"

on line one. Of course, you don't always want it to be written to line one, right? Maybe you want this bit of code to be written on line 3 in order to keep your code organize. Is there a way to do this? Absolutely! Simply add the line number as a second parameter to the function. For example, we want to have this bit of code written on line 3, we would set up our Example.au3 file to look like this.

#Include "_includeDir.au3"
#Include <File.au3> ; Not needed. Just here as an example of a normal script.
#Include <Array.au3> ; Not needed. Just here as example of normal script.
_includeDir("Directory to Include", 3)

MsgBox(0,"Example","This is just an example!")

See how we added the 3 to the end of _includeDir? This will tell the function to write the #Include "IncludeDirUDF\loadIncludes.au3" on line 3 of Example.au3. Note, the line HAS TO EXIST in order to be written to it. For example, if your Example.au3 code only has 6 lines, and you specify to be written on line 7, it WILL NOT WORK.

 

The code is designed to include and restart in order to process the included files. For some reason, if you want to JUST generate the included file and NOT restart, you can add one more parameter to the code. If you don't want the code to restart, simply set your code up to look like this:

#Include "_includeDir.au3"
#Include <File.au3> ; Not needed. Just here as an example of a normal script.
#Include <Array.au3> ; Not needed. Just here as example of normal script.
_includeDir("Directory to Include", 3, False)

MsgBox(0,"Example","This is just an example!")

Note, if you set this last parameter to false, it will simply generate the included file and write to line 3 of Example.au3 (As specified before) and exit before the code reaches the MsgBox() and it will not be displayed.

 

The last important thing to note: In order to re-include a different set of files, you must delete the #Include "IncludeDirUDF\loadIncludes.au3" from your main script (In this case, Example.au3) and delete the generated file, IncludeDirUDF. Now you can simply rerun Example.au3 and it will include any the dir with any changes you made to it. Only .au3 files should be in the directory you're trying to include as it will not process the other files and will generate an error.

 

I hope this UDF helps somebody out! Comment any questions/concerns you may have and I will try to address them as soon as possible!

 

Thanks,

Timothy

CEO - Amarok Studios

_includeDir.au3

Share this post


Link to post
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

  • Similar Content

    • Fhelipe
      By Fhelipe
      So I wanted to use my machine as a server for a program that had a unique login system. It can only log in 1 person and the password is in the script itself. I would like to adptar my code or change it completely so that I can create a database and the Script At Time Of Login Get Database Login And Log In
      Experience with Autoit: Basic                      (sorry for bad English)
      Experience with SQL: None                              (translator only)
      Code Currently Used To Login:
      ;=========================================================
      While 1
          $MSG = GUIGetMsg()
          Switch $MSG
          Case $ButtonOk
              If VerifyLogin(GUICtrlRead($USERNAME),GUICtrlRead($PASSWORD)) = 1 Then
                  GUIDelete($Form1)
                  MsgBox(-1,"Logado com Sucesso","Login Sucedido, Para Parar o Aimbot Pressione ESC!")
                  Run ("C:\Program Files (x86)\Steam\steamapps\common\Mitos.is The Game\Mitosis.exe")
                  RunP()
              Else
                  MsgBox(-1,"Error","Usúario ou Senha está incorreto, Ou Ainda Não Pagou!")
               EndIf
          Case -3
              Exit
           Case $ButtonCancel
              Exit
                Case $HelpButton
               MsgBox(-1, "Criadores", "Criadores: Zummey & Ralta")
      Case $Register
         MsgBox(-1, "ERRO", "PROGRAMA EM DESENVOLVIMENTO FUNÇÃO DESABILITADA")
          EndSwitch
      WEnd
      Func VerifyLogin($USERNAME,$PASSWORD)
          If $USERNAME = "Zummey" And $PASSWORD = "xd90fe10" Then
              Return 1
          Else
              Return 0
          EndIf
      EndFunc; End login
      ;=========================================================
    • IamKJ
      By IamKJ
      I am trying to allow the GUI to gather info as to when to execute a function.  I am having trouble doing this.  So far this is what I have.
       
      ;Timer Func timer () If Not IsDeclared("iMsgBoxAnswer") Then Local $iMsgBoxAnswer $iMsgBoxAnswer = MsgBox(36,"Timer","Please format your answer in 00:00:00:000") Select Case $iMsgBoxAnswer = 6 ;Yes Global $infotime = InputBox ('Time', 'What time to execute?') Do $rawtimer = ToolTip(@Hour & ':' & @Min & ':' & @Sec & ':' & _MSec()) until $rawtimer = $infotime if $rawtimer = $infotime Then msgbox (0,'Worked','Worked') Else EndIf Case $iMsgBoxAnswer = 7 ;No Exit EndSelect EndFunc Func _MSec() Local $stSystemTime = DllStructCreate('ushort;ushort;ushort;ushort;ushort;ushort;ushort;ushort') DllCall('kernel32.dll', 'none', 'GetSystemTime', 'ptr', DllStructGetPtr($stSystemTime)) $sMilliSeconds = StringFormat('%03d', DllStructGetData($stSystemTime, 8)) $stSystemTime = 0 Return $sMilliSeconds EndFunc I have also tried _GUIToolTip_GetText in order to read the tooltip until the time specified, but it still doesn't work.  Any help would be great.
    • IamKJ
      By IamKJ
      So I have a lot of different functions in the little program I'm making.  Most of them use the Do statement, such as finding images, clicking buttons, etc.
       
      The question I have is how would I be able to both
      1) Create a hotkey to pause whatever I am doing at the moment.  If I have to put something into every function in the program, I don't mind.
      2) Create a hotkey to exit whatever I am doing and stop all loops or commands and bring back the main GUI?
    • Manivel
      By Manivel
      Hi,
      Can any one please share the Connection string for SQL Developer. 
      How to Connect the SQL Developer from AutoIT. We need to execute the query through AutoIt. is that possible ?
    • Manivel
      By Manivel
      We are launching the AutoIT script through selenium and passing the values through command lines.
      Similarly able to return the value from AutoIt to selenium ?  If yes ? how to return the values ?