Sign in to follow this  
Followers 0
Erion

A question regarding _PathSplit()

11 posts in this topic

Hello all,

I'm wondering, why does the _PathSplit function take 4 additional parameters (drive, directory, filename and extension)?

Checking the code it seems to me that everything is in the first parameter (path) and the function splits it into segments. Also, it returns an array with the results which can be found in the last 4 parameters of the function. I'm sort of confused, wouldn't just a path parameter be enough with a single array returning the results?

Erion

Share this post


Link to post
Share on other sites



Hello all,

I'm wondering, why does the _PathSplit function take 4 additional parameters (drive, directory, filename and extension)?

Checking the code it seems to me that everything is in the first parameter (path) and the function splits it into segments. Also, it returns an array with the results which can be found in the last 4 parameters of the function. I'm sort of confused, wouldn't just a path parameter be enough with a single array returning the results?

Erion

The idea is that you have variables already declared for directory, filename etc and the function assigns values to those variables. Note the parameters have ByRef declarations in the function. It's just a way to pass the results back when you have more than one result. It could have been done instead by returning an array for example. So you would use it like this maybe

#Include <File.au3>
Global   $szDrive,  $szDir,  $szFName,  $szExt

$szPath = @ScriptDir;but we don't know what drive it is using or which folder
_PathSplit($szPath,  $szDrive,  $szDir,  $szFName,  $szExt)

ConsoleWrite("This script is running on drive " & $szDrive & ', in folder ' & $szFName & @CRLF)

Serial port communications UDF Includes functions for binary transmission and reception.printing UDF Useful for graphs, forms, labels, reports etc.Add User Call Tips to SciTE for functions in UDFs not included with AutoIt and for your own scripts.Functions with parameters in OnEvent mode and for Hot Keys One function replaces GuiSetOnEvent, GuiCtrlSetOnEvent and HotKeySet.UDF IsConnected2 for notification of status of connected state of many urls or IPs, without slowing the script.

Share this post


Link to post
Share on other sites

Hello,

Thank you very much for your reply.

I see that it sets those variables based on the path, but what's the point in setting variables and returning an array? Somehow it isn't a good idea.

If I'd like to use the array it returns, I'm still forced to declare variables and pass them as the last 4 arguments when I won't ever use them. I think it would be much better to have the results as an array and remove the 4 parameters altogether.

Maybe it's just me, but that function is a bit weird, i.e. returning the results in two ways. Anyways, I thought I'd mention it.

Thanks again,

Erion

Share this post


Link to post
Share on other sites

Hello,

Thank you very much for your reply.

I see that it sets those variables based on the path, but what's the point in setting variables and returning an array? Somehow it isn't a good idea.

If I'd like to use the array it returns, I'm still forced to declare variables and pass them as the last 4 arguments when I won't ever use them. I think it would be much better to have the results as an array and remove the 4 parameters altogether.

Maybe it's just me, but that function is a bit weird, i.e. returning the results in two ways. Anyways, I thought I'd mention it.

Thanks again,

Erion

Yes, I see what you mean. My guess is that the function was first written using ByRef, then later changed to return an array (maybe when it was updated in 2005) but the parameters were kept for compatibility with the old version. But I don't really know.

Serial port communications UDF Includes functions for binary transmission and reception.printing UDF Useful for graphs, forms, labels, reports etc.Add User Call Tips to SciTE for functions in UDFs not included with AutoIt and for your own scripts.Functions with parameters in OnEvent mode and for Hot Keys One function replaces GuiSetOnEvent, GuiCtrlSetOnEvent and HotKeySet.UDF IsConnected2 for notification of status of connected state of many urls or IPs, without slowing the script.

Share this post


Link to post
Share on other sites

I agree, it's not always convinient to set extra paramters to pass ByRef when you just need to get one part of the path.

I was confused about it too when i just started to use AutoIt.


 

Spoiler

Using OS: Win 7 Professional, Using AutoIt Ver(s): 3.3.6.1 / 3.3.8.1

AutoIt_Rus_Community.png AutoIt Russian Community

My Work...

Spoiler

AutoIt_Icon_small.pngProjects: ATT - Application Translate Tool {new}| BlockIt - Block files & folders {new}| SIP - Selected Image Preview {new}| SISCABMAN - SciTE Abbreviations Manager {new}| AutoIt Path Switcher | AutoIt Menu for Opera! | YouTube Download Center! | Desktop Icons Restorator | Math Tasks | KeyBoard & Mouse Cleaner | CaptureIt - Capture Images Utility | CheckFileSize Program

AutoIt_Icon_small.pngUDFs: OnAutoItErrorRegister - Handle AutoIt critical errors {new}| AutoIt Syntax Highlight {new}| Opera Library! | Winamp Library | GetFolderToMenu | Custom_InputBox()! | _FileRun UDF | _CheckInput() UDF | _GUIInputSetOnlyNumbers() UDF | _FileGetValidName() UDF | _GUICtrlCreateRadioCBox UDF | _GuiCreateGrid() | _PathSplitByRegExp() | _GUICtrlListView_MoveItems - UDF | GUICtrlSetOnHover_UDF! | _ControlTab UDF! | _MouseSetOnEvent() UDF! | _ProcessListEx - UDF | GUICtrl_SetResizing - UDF! | Mod. for _IniString UDFs | _StringStripChars UDF | _ColorIsDarkShade UDF | _ColorConvertValue UDF | _GUICtrlTab_CoverBackground | CUI_App_UDF | _IncludeScripts UDF | _AutoIt3ExecuteCode | _DragList UDF | Mod. for _ListView_Progress | _ListView_SysLink | _GenerateRandomNumbers | _BlockInputEx | _IsPressedEx | OnAutoItExit Handler | _GUICtrlCreateTFLabel UDF | WinControlSetEvent UDF | Mod. for _DirGetSizeEx UDF
 
AutoIt_Icon_small.pngExamples: 
ScreenSaver Demo - Matrix included | Gui Drag Without pause the script | _WinAttach()! | Turn Off/On Monitor | ComboBox Handler Example | Mod. for "Thinking Box" | Cool "About" Box | TasksBar Imitation Demo

Like the Projects/UDFs/Examples? Please rate the topic (up-right corner of the post header: Rating AutoIt_Rating.gif)

* === My topics === *

==================================================
My_Userbar.gif
==================================================

 

 

 

AutoIt is simple, subtle, elegant. © AutoIt Team

Share this post


Link to post
Share on other sites

#6 ·  Posted (edited)

Sadly you can't have optional BYRef params either, that would be nice!

If you want you can make your own function, just take pathsplit and edit out anything referring to the vars. Looking at the code by valik, its realy easy, just take out the last 4 params in the function bit, and teke out the setting of the values towards the end of the function. No messing round with the internals!

MDiesel

; #FUNCTION# =====================================================================================================================
; Name...........: __PathSplit
; Description ...: Splits a path into the drive, directory, file name and file extension parts. An empty string is set if a part is missing.
; Syntax.........: __PathSplit($szPath, ByRef $szDrive, ByRef $szDir, ByRef $szFName, ByRef $szExt)
; Parameters ....: $szPath  - The path to be split (Can contain a UNC server or drive letter)
; Return values .: Success - Returns an array with 5 elements where 0 = original path, 1 = drive, 2 = directory, 3 = filename, 4 = extension
; Author ........: Valik
; Modified.......: MDiesel
; Remarks .......: This function does not take a command line string. It works on paths, not paths with arguments.
; Related .......: 
; Link ..........;
; Example .......; yes:
#cs
$Path = _PathSplit("c:\Documents and settings\stuff\morestuff.au3")
For $i = 0 to 4
MsgBox (0, $i, $Path[$i])
Next
#ce
; ================================================================================================================================

Func __PathSplit($szPath)
    ; Set local strings to null (We use local strings in case one of the arguments is the same variable)
    Local $drive = ""
    Local $dir = ""
    Local $fname = ""
    Local $ext = ""
    Local $pos

    ; Create an array which will be filled and returned later
    Local $array[5]
    $array[0] = $szPath; $szPath can get destroyed, so it needs set now

    ; Get drive letter if present (Can be a UNC server)
    If StringMid($szPath, 2, 1) = ":" Then
        $drive = StringLeft($szPath, 2)
        $szPath = StringTrimLeft($szPath, 2)
    ElseIf StringLeft($szPath, 2) = "\\" Then
        $szPath = StringTrimLeft($szPath, 2) ; Trim the \\
        $pos = StringInStr($szPath, "\")
        If $pos = 0 Then $pos = StringInStr($szPath, "/")
        If $pos = 0 Then
            $drive = "\\" & $szPath; Prepend the \\ we stripped earlier
            $szPath = ""; Set to null because the whole path was just the UNC server name
        Else
            $drive = "\\" & StringLeft($szPath, $pos - 1) ; Prepend the \\ we stripped earlier
            $szPath = StringTrimLeft($szPath, $pos - 1)
        EndIf
    EndIf

    ; Set the directory and file name if present
    Local $nPosForward = StringInStr($szPath, "/", 0, -1)
    Local $nPosBackward = StringInStr($szPath, "\", 0, -1)
    If $nPosForward >= $nPosBackward Then
        $pos = $nPosForward
    Else
        $pos = $nPosBackward
    EndIf
    $dir = StringLeft($szPath, $pos)
    $fname = StringRight($szPath, StringLen($szPath) - $pos)

    ; If $szDir wasn't set, then the whole path must just be a file, so set the filename
    If StringLen($dir) = 0 Then $fname = $szPath

    $pos = StringInStr($fname, ".", 0, -1)
    If $pos Then
        $ext = StringRight($fname, StringLen($fname) - ($pos - 1))
        $fname = StringLeft($fname, $pos - 1)
    EndIf

    ; Set the array to what we found
    $array[1] = $drive
    $array[2] = $dir
    $array[3] = $fname
    $array[4] = $ext
    Return $array
EndFunc ; ==> __PathSplit
Edited by mdiesel

Share this post


Link to post
Share on other sites

Hello,

Thanks for the code, a few hours ago I did exactly the same trimming. Is there a way to update the function to this one in a later release? Should I post it to somewhere else as a suggestion for the devs?

Erion

Share this post


Link to post
Share on other sites

Erion

Personally, I do not use _PathSplit().

I find it is easier, faster, more efficient to obtain the required sub-string from the path-filename string with a StringRegExpReplace() one liner.

I select the appropiate one or two StringRegExpReplace() one liners required from this file to use in my script.

Malkey

;
Local $sFile = "C:\Program Files\Another Dir\AutoIt3\AutoIt3.chm"

; Drive letter -                                    Example returns     "C"
Local $sDrive = StringRegExpReplace($sFile, ":.*$", "")

; Full Path with backslash -                        Example returns     "C:\Program Files\Another Dir\AutoIt3\"
Local $sPath = StringRegExpReplace($sFile, "(^.*\\)(.*)", "\1")

; Full Path without backslash -                     Example returns     "C:\Program Files\Another Dir\AutoIt3"
Local $sPathExDr = StringRegExpReplace($sFile, "(^.:)(\\.*\\)(.*$)", "\2")

; Full Path w/0 backslashes, nor drive letter -     Example returns     "\Program Files\Another Dir\AutoIt3\"
Local $sPathExDrBSs = StringRegExpReplace($sFile, "(^.:\\)(.*)(\\.*$)", "\2")

; Path w/o backslash, not drive letter: -           Example returns     "Program Files\Another Dir\AutoIt3"
Local $sPathExBS = StringRegExpReplace($sFile, "(^.*)\\(.*)", "\1")

; File name with ext -                              Example returns     "AutoIt3.chm"
Local $sFilName = StringRegExpReplace($sFile, "^.*\\", "")

; File name w/0 ext -                               Example returns     "AutoIt3"
Local $sFilenameExExt = StringRegExpReplace($sFile, "^.*\\|\..*$", "")

; Dot Extenstion -                                  Example returns     ".chm"
Local $sDotExt = StringRegExpReplace($sFile, "^.*\.", ".$1")

; Extenstion -                                      Example returns     "chm"
Local $sExt = StringRegExpReplace($sFile, "^.*\.", "")

MsgBox(0, "Path File Name Parts", _
        "Drive           " & @TAB & $sDrive & @CRLF & _
        "Path             " & @TAB & $sPath & @CRLF & _
        "Path w/o backslash" & @TAB & $sPathExBS & @CRLF & _
        "Path w/o Drv:   " & @TAB & $sPathExDr & @CRLF & _
        "Path w/o Drv or \'s" & @TAB & $sPathExDrBSs & @CRLF & _
        "File Name       " & @TAB & $sFilName & @CRLF & _
        "File Name w/o Ext " & @TAB & $sFilenameExExt & @CRLF & _
        "Dot Extension   " & @TAB & $sDotExt & @CRLF & _
        "Extension       " & @TAB & $sExt & @CRLF)
;

Share this post


Link to post
Share on other sites

Erion

Personally, I do not use _PathSplit().

I find it is easier, faster, more efficient to obtain the required sub-string from the path-filename string with a StringRegExpReplace() one liner.

I select the appropiate one or two StringRegExpReplace() one liners required from this file to use in my script.

Malkey

;
           Local $sFile = "C:\Program Files\Another Dir\AutoIt3\AutoIt3.chm"
           
          ; Drive letter -                                   Example returns     "C"
           Local $sDrive = StringRegExpReplace($sFile, ":.*$", "")
           
          ; Full Path with backslash -                       Example returns     "C:\Program Files\Another Dir\AutoIt3\"
           Local $sPath = StringRegExpReplace($sFile, "(^.*\\)(.*)", "\1")
           
          ; Full Path without backslash -                    Example returns     "C:\Program Files\Another Dir\AutoIt3"
           Local $sPathExDr = StringRegExpReplace($sFile, "(^.:)(\\.*\\)(.*$)", "\2")
           
          ; Full Path w/0 backslashes, nor drive letter -    Example returns     "\Program Files\Another Dir\AutoIt3\"
           Local $sPathExDrBSs = StringRegExpReplace($sFile, "(^.:\\)(.*)(\\.*$)", "\2")
           
          ; Path w/o backslash, not drive letter: -          Example returns     "Program Files\Another Dir\AutoIt3"
           Local $sPathExBS = StringRegExpReplace($sFile, "(^.*)\\(.*)", "\1")
           
          ; File name with ext -                                 Example returns     "AutoIt3.chm"
           Local $sFilName = StringRegExpReplace($sFile, "^.*\\", "")
           
          ; File name w/0 ext -                              Example returns     "AutoIt3"
           Local $sFilenameExExt = StringRegExpReplace($sFile, "^.*\\|\..*$", "")
           
          ; Dot Extenstion -                                     Example returns     ".chm"
           Local $sDotExt = StringRegExpReplace($sFile, "^.*\.", ".$1")
           
          ; Extenstion -                                         Example returns     "chm"
           Local $sExt = StringRegExpReplace($sFile, "^.*\.", "")
           
           MsgBox(0, "Path File Name Parts", _
                   "Drive            " & @TAB & $sDrive & @CRLF & _
                   "Path              " & @TAB & $sPath & @CRLF & _
                   "Path w/o backslash" & @TAB & $sPathExBS & @CRLF & _
                   "Path w/o Drv:    " & @TAB & $sPathExDr & @CRLF & _
                   "Path w/o Drv or \'s" & @TAB & $sPathExDrBSs & @CRLF & _
                   "File Name        " & @TAB & $sFilName & @CRLF & _
                   "File Name w/o Ext " & @TAB & $sFilenameExExt & @CRLF & _
                   "Dot Extension    " & @TAB & $sDotExt & @CRLF & _
                   "Extension        " & @TAB & $sExt & @CRLF)
          ;
I like those Malkey.

mgrefmalkeypathsplit


Serial port communications UDF Includes functions for binary transmission and reception.printing UDF Useful for graphs, forms, labels, reports etc.Add User Call Tips to SciTE for functions in UDFs not included with AutoIt and for your own scripts.Functions with parameters in OnEvent mode and for Hot Keys One function replaces GuiSetOnEvent, GuiCtrlSetOnEvent and HotKeySet.UDF IsConnected2 for notification of status of connected state of many urls or IPs, without slowing the script.

Share this post


Link to post
Share on other sites

Thanks for this, it's more elegant indeed.

Erion

Share this post


Link to post
Share on other sites

#11 ·  Posted (edited)

I have this function that using RegExp to get parts from path: _PathSplitByRegExp()

I am using it always (or seperate parts from it).

But here is one that can make _PathSplit more usable (idea by Valik):

#include <File.au3>
#include <Array.au3>
;

$aPath = _FileSplitPath("C:\Program Files\Some App\Some File.exe")

_ArrayDisplay($aPath)

Func _FileSplitPath($sFile)
    Local $sDir, $sPath, $sFName, $sFExt
    _PathSplit($sFile, $sDir, $sPath, $sFName, $sFExt)
    Local $aRet[5] = [$sFile, $sDir, $sPath, $sFName, $sFExt]
    
    Return $aRet
EndFunc
Edited by MrCreatoR

 

Spoiler

Using OS: Win 7 Professional, Using AutoIt Ver(s): 3.3.6.1 / 3.3.8.1

AutoIt_Rus_Community.png AutoIt Russian Community

My Work...

Spoiler

AutoIt_Icon_small.pngProjects: ATT - Application Translate Tool {new}| BlockIt - Block files & folders {new}| SIP - Selected Image Preview {new}| SISCABMAN - SciTE Abbreviations Manager {new}| AutoIt Path Switcher | AutoIt Menu for Opera! | YouTube Download Center! | Desktop Icons Restorator | Math Tasks | KeyBoard & Mouse Cleaner | CaptureIt - Capture Images Utility | CheckFileSize Program

AutoIt_Icon_small.pngUDFs: OnAutoItErrorRegister - Handle AutoIt critical errors {new}| AutoIt Syntax Highlight {new}| Opera Library! | Winamp Library | GetFolderToMenu | Custom_InputBox()! | _FileRun UDF | _CheckInput() UDF | _GUIInputSetOnlyNumbers() UDF | _FileGetValidName() UDF | _GUICtrlCreateRadioCBox UDF | _GuiCreateGrid() | _PathSplitByRegExp() | _GUICtrlListView_MoveItems - UDF | GUICtrlSetOnHover_UDF! | _ControlTab UDF! | _MouseSetOnEvent() UDF! | _ProcessListEx - UDF | GUICtrl_SetResizing - UDF! | Mod. for _IniString UDFs | _StringStripChars UDF | _ColorIsDarkShade UDF | _ColorConvertValue UDF | _GUICtrlTab_CoverBackground | CUI_App_UDF | _IncludeScripts UDF | _AutoIt3ExecuteCode | _DragList UDF | Mod. for _ListView_Progress | _ListView_SysLink | _GenerateRandomNumbers | _BlockInputEx | _IsPressedEx | OnAutoItExit Handler | _GUICtrlCreateTFLabel UDF | WinControlSetEvent UDF | Mod. for _DirGetSizeEx UDF
 
AutoIt_Icon_small.pngExamples: 
ScreenSaver Demo - Matrix included | Gui Drag Without pause the script | _WinAttach()! | Turn Off/On Monitor | ComboBox Handler Example | Mod. for "Thinking Box" | Cool "About" Box | TasksBar Imitation Demo

Like the Projects/UDFs/Examples? Please rate the topic (up-right corner of the post header: Rating AutoIt_Rating.gif)

* === My topics === *

==================================================
My_Userbar.gif
==================================================

 

 

 

AutoIt is simple, subtle, elegant. © AutoIt Team

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
Sign in to follow this  
Followers 0