[Gambas-user] Size of a directory

Fabien Bodard gambas.fr at gmail.com
Sat Sep 22 09:04:10 CEST 2018


Le ven. 21 sept. 2018 17:47, Tony Morehen <tmorehen at ajm-software.com> a
écrit :

> Here's an all Gambas function.  It's recursive and includes the size of
> the original directory.  It's comparable in speed to du.
>
> Public Function ScanDir(sDir As String) As Long
>
>    Dim sFile As String
>    Dim sPath As String
>    Dim hStat As Stat
>    Dim aDir As String[]
>    Dim iSize As Long
>
>    Try hStat = Stat(sDir)
>    If Error Then Return -1
>    iSize = hStat.Size
>    If hStat.Type <> gb.Directory Then Return iSize
>    Try aDir = Dir(sDir)
>
>    For Each sFile In aDir
>
>      sPath = sDir &/ sFile
>      Try hStat = Stat(sPath)
>      If Error Then Continue
>
>      With hStat
>        If .Type = gb.Directory Then
>          Try iSize += ScanDir(sPath)
>        Endif
>        Try iSize += .Size
>      End With
>    Next
>    Return iSize
>
> End
>

This is not a bad function but there is some little things illogical.

You must not manage errors is the function as it return in this case a
false value not managed. It is better if you let Gambas propagate an error
you manage then on the initial call.

Public Function ScanDir(sDir As String) As Long

   Dim sFile As String
   Dim sPath As String
   Dim hStat As Stat
   Dim iSize As Long
   'Generate an error if it is not a dir

   For Each sFile In Dir (sDir)

     sPath = sDir &/ sFile
     hStat = Stat(sPath)
     With hStat
       If .Type = gb.Directory Then
         iSize += ScanDir(sPath)
       Endif
       iSize += .Size
     End With
   Next
   Return iSize

End

Use will be

Try ISize =Scandir (sDir)

If error  then... it is not possible to get the dir size.

In this function we can (need) add management for links


--
Fabien

>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.gambas-basic.org/pipermail/user/attachments/20180922/adcaa08b/attachment.html>


More information about the User mailing list