User Tools

Site Tools


k6:k6.3:start

6.3 File and Directory Functions

These file and directory functions as well as supplementary functions are presented in the following sections:

  • 6.3.1 COPY … TO …
  • 6.3.2 DFREE
  • 6.3.3 EXIST
  • 6.3.4 ISDIR
  • 6.3.5 KILL
  • 6.3.6 RMDIR
  • 6.3.7 LINK
  • 6.3.8 MKDIR
  • 6.3.9 MOVE … TO …
  • 6.3.10 MOVE … KILL
  • 6.3.11 DIR
  • 6.3.12 RDIR
  • 6.3.13 Digression 1 - Determining the size of a directory
  • 6.3.14 Digression 2 - Creating a file
  • 6.3.15 Digression 3 - Copying a directory

6.3.1 COPY ... TO ...

COPY SourcePath TO DestinationPath
  • This instruction copies a file from the source SourcePath to the destination DestinationPath.
  • The destination path does not have to have the same (base) name as the source path.
  • Note that you cannot copy directories recursively with this instruction!
  • An error (error number 38) is triggered if the target file already exists.
  • This instruction internally uses the functions, OPEN, READ, WRITE and CLOSE, which is why all the associated error messages can also occur and the timestamps do not match those of the original file.

Example 1:

Public sScriptPath As String
Public sTempScriptPath As String
 
Public Sub Form_Open()
 
  sScriptPath = "./data/test_script.sh"
  sTempScriptPath = Temp(File.BaseName(sScriptPath))
 
  Copy sScriptPath To sTempScriptPath
  Chmod sTempScriptPath To "r-xr-x---"
  …
 
End

A bash script is copied from the data folder inside the project folder into a temporary file /tmp/gambas.1000/5503/test_script.tmp. This is necessary here because only then are the permissions set so that the script becomes executable for the user and the group.

Example 2:

Public Sub btnCopyFile_Click()
 
' Based on an idea by Willy Raets
  Dim sSourcePath, sDestinationPath, sFilename As String
 
  sSourcePath = User.Home &/ "DW"
  sDestinationPath = User.Home &/ "GB3BUCH"
  sFileName = "dokuwiki_syntax.txt"
 
' Check whether the file to be copied exists.
  If Exist(sSourcePath &/ sFileName) Then
   ' Now check if copyto directory exists
     If Not Exist(sDestinationPath) Then
        Try Mkdir sDestinationPath
        If Error Then
           Message.Error("Error! " & Error.Text)
           Return
        Endif
     Endif
  ' Now check if copyto file exists
    If Not (Exist(sDestinationPath & sFileName)) Then
       Try Copy sSourcePath &/ sFileName To sDestinationPath &/ sFileName
    Else
     ' If Exists first remove old file then copy new file
       Kill sDestinationPath &/ sFileName
       Try Copy sSourcePath &/ sFileName To sDestinationPath &/ sFileName
       If Error Then
          Message.Error("Error! " & Error.Text)
          Return
       Endif
    Endif
  Else
     Message.Error("File not exist: " & sFileName)
     Return
  Endif
 
  Message.Info("File '" & sFileName & "' successfully copied!")
 
End

The text file dokuwiki_syntax.txt from the directory /home/hans/DW is copied to the directory /home/hans/GB3BUCH. Various checks and messages ensure successful copying of the specified file.

6.3.2 DFREE

DFree( sPath AS String ) AS Long

Returns the size of the free space (in bytes) of the mass storage on which the directory sPath is located. Always compare the result with a comparison value of long integer data type, as storage media can have more than 2^32 bytes capacity.

Example 1:

Dim ilFree As Long

ilFree = DFree(User.Home &/ "DW") ' 346.218.151.936
Print Round(ilFree / 10 ^ 9, -3) & " GB" ' 346.218 GB

Interpret the result to mean that there is about 346 GB of free space left on the hard disk in the author's PC.

Example 2:

Print DFree(“/media/hans/USB-STICK“)

To determine the size of the free space on the connected USB stick in the Gambas console.

6.3.3 EXIST

Exist( sPath ) As Boolean

Indicates whether a file or directory with the path sPath exists.

Example:

If Not Exist(User.Home &/ "Destination") Then
   MkDir(User.Home &/ "Destination")
Endif

The directory 'Destination' is only created with the specified path if it does not exist.

6.3.4 ISDIR

IsDir ( sPath AS String ) AS Boolean

Returns True if the path specification points to a directory. If the path sPath does not exist or if the path does not point to a directory, then this function returns False.

Example:

Dim sPath As String
 
sPath = User.Home &/ "test33"
If Not Exist(sPath) Then Mkdir sPath
Print "Is Directory? = "; IsDir(sPath) ' TRUE
sPath = User.Home &/ "test34"
If Not Exist(sPath) Then File.Save(sPath, "CONTENT")
Print "Is Directory? = "; IsDir(sPath) ' FALSE

In a directory, no file can have the same name as a directory. Hence the change from test33 to test34.

6.3.5 KILL

KILL FilePath

Deletes an existing file whose (absolute) path is in the string FilePath.

Example:

Dim sSourcePath, sDestinationPath As String
 
sSourcePath = "./css" &/ fCSSFileName
sDestinationPath = sWorkDirectory &/ "css" &/ fCSSFileName
 
If Stat(sSourcePath).LastChange > Stat(sDestinationPath).LastChange Then
   Try Kill sDestinationPath
   Try Copy sSourcePath To  sDestinationPath
Endif

If a more recent css file exists in the 'css' directory in the project directory, then the original css file is deleted and the current css file is copied to the existing working directory.

On the other hand, if you want to delete a directory, use the following RMDIR statement.

6.3.6 RMDIR

RMDIR DirectoryPath

Deletes the directory specified by DirectoryPath, but it must be empty!

Example:

If RDir(DirectoryPath).Count > 0 Then
   Message.Warning("The specified directory is not empty and therefore cannot be deleted.")
   Return
Else
   Try Rmdir DirectoryPath
   Message.Info("The specified directory was successfully deleted!")
Endif

First it is checked whether the specified directory is empty. If the directory is empty, it is deleted - otherwise a warning is issued and the deletion process is aborted.

Note: For a good alternative, use the function Shell.RmDir( DirectoryPath As String) from the component gb.util. It removes the specified directory by removing its entire contents recursively!

LINK sOriginalPath TO sSoftLinkPath

Creates a symbolic link (softlink) with path sSoftLinkPath pointing to the target file or directory sOriginalPath.

Example:

Dim sSoftLinkPath, sOriginalPath As String
 
sOriginalPath = "/home/hans/DW/0_DW_Convert/librewriter2dokuwiki.gambas"
sSoftLinkPath = "/home/hans/Schreibtisch/Formatting_DokuWiki_Tables"
 
If Not Exist(sSoftLinkPath) Then
   Try Link sOriginalPath To sSoftLinkPath
   If Error Then Message.Error(Error.Text)
Endif

A permanent link is created on the desktop with the name 'Formatting_DokuWiki_Tables' to a Gambas executable file.

6.3.8 MKDIR

MKDIR DirectoryPath

Creates the directory specified by DirectoryPath. By default, the MKDIR command creates a directory with the rights 0755. If you need other rights, set them with the CHMOD instruction. If at least one parent directory of the specified path does not exist, an error is triggered.

Example:

Dim sDirectoryPath As String
Dim FileInfo As Stat
 
sDirectoryPath = User.Home &/ "Test18"
 
If Not Exist(sDirectoryPath) Then
   Mkdir sDirectoryPath
   FileInfo = Stat(sDirectoryPath)
   Print Oct(FileInfo.Mode) ' Output: 755
Endif

Only if the specified directory does not exist, it will be created. With the value of the Mode property of the Stat object FileInfo, you can display the rights of the created directory in a suitable format.

Note: As an alternative, use the Shell.MkDir( DirectoryPath As String) function from the gb.util component, as a directory with DirectoryPath as the directory path and all its parent (parent) directories will be created.

6.3.9 MOVE ... TO ...

MOVE OldName TO NewName

Renames or moves a file or directory. Oldname and NewName can be in different directories - but must be on the same device!

Alternatively, use the function Move(Source As String, Destination As String) with Source as the path of the source file and Destination as the destination path. This function moves a file or directory - even if they are on different devices.

Example 1:

If you want to move a file - regardless of its location - proceed like this:

Try Move OldFilePath To NewFilePath
If Error Then
   Try Copy OldFilePath To NewFilePath
   If Not Error Then Kill OldFilePath
Endif

A file A with the path OldFilePath is moved. If an error occurs, the file A with the path OldFilePath is copied to NewFilePath. If no error occurs, the file A is finally deleted.

Example 2:

Public Sub RenameDirectory(OldDirPath As String, NewDirPath As String)
 
  Try Move OldDirPath To NewDirPath
  If Error Then
     Message.Error("Error when renaming." & gb.Lf & Error.Text & " !")
     Return
  Endif
 
End
 
Public Sub btnRenameDirectory_Click()
  RenameDirectory(User.Home &/ "Test18", User.Home &/ "Test19")
End

The first time the procedure is called, the directory Test18 is renamed to Test19. With each subsequent call, an error is triggered and the error message 'Error when renaming. File already exists!' is displayed.

Example 3:

Public Sub MoveDirectory(OldDirPath As String, NewDirPath As String)
 
  Try Move OldDirPath To NewDirPath
  If Error Then
     Message.Error("Error when moving." & gb.Lf & Error.Text & " !")
     Print Error.Text
     Return
  Endif
 
End
 
Public Sub btnMoveDirectory_Click()
  MoveDirectory(User.Home &/ "Test18", User.Home &/ "TWX" &/ "Test18")
End

The first time the procedure is called, the directory Test18 is moved to the existing directory TWX. With each subsequent call, an error is triggered and the error message 'Error when renaming. File already exists!' is displayed.

6.3.10 MOVE ... KILL

MOVE OldName KILL NewName
MOVE OldName DOWNTO NewName ' Considered obsolete

Renames or moves a file or directory, deleting the target file first, and the two operations are atomic. OldName and NewName can be in different directories but must be on the same device. Normally, moving an existing file will trigger the 'file already exists' error. In this case, the kill instruction acts like an option that first deletes the file existing in the target and only then moves the file.

The function replaces the MOVE OldName DOWNTO NewName function chain, which is considered obsolete.

Example:

Public Sub btnMoveKill_Click()
 
  Dim sSourcePath, sDestinationPath, sFilename As String
 
  sSourcePath = User.Home &/ "DW"
  sDestinationPath = User.Home &/ "GB3BUCH"
  sFileName = "dokuwiki_syntax.txt"
 
' Check whether the file to be moved exists.
  If Exist(sSourcePath &/ sFileName) Then
   ' Now check if moveto directory exists
     If Not Exist(sDestinationPath) Then
        Try Mkdir sDestinationPath
        If Error Then
           Message.Error("Error! " & Error.Text)
           Return
        Endif
     Endif
  ' Now the file is moved …
    Move sSourcePath &/ sFileName Kill sDestinationPath &/ sFileName
  Else
     Message.Error("File not exist: " & sFileName)
     Return
  Endif
 
  Message.Info("File '" & sFileName & "' successfully moved!")
 
End

Variant:

Public Sub btnMoveKill_Click()
 
  Dim sSourcePath, sDestinationPath, sFilename As String
 
   sSourcePath = User.Home &/ "DW"
   sDestinationPath = User.Home &/ "GB3BUCH"
   sFileName = "dokuwiki_syntax.txt"
 
  Move sSourcePath &/ sFileName Kill sDestinationPath &/ sFileName
  Message.Info("File '" & sFileName & "' successfully moved!")
 
  Catch
    Message.Error(Error.Text)
 
End

The file 'dokuwiki_syntax.txt is moved after both variants. If a file with the same name already exists in the target directory, it will be (automatically) deleted beforehand - without generating an error.

6.3.11 DIR

ArrayOfFilenames = Dir ( sDirectory AS String [ , Pattern AS String , Filter AS Integer ] ) AS String[]

The function returns a string array containing only the names of the files and directories in the specified directory sDirectory that match the pattern and filter. You must assemble the file path from the file or directory names and the sDirectory parameter.

  • Pattern (optional) can contain the same generic characters as the LIKE operator. If no pattern is specified, then the name of each file and directory found will be returned.
  • filter (optional) specifies whether only the names of files or only of directories or both are returned. If no filter is specified, the names of all files and directories in the specified directory that match the pattern are returned.

The filter can be one of the following constants:

  • gb.file to return only files.
  • gb.Directory to return only directory names,
  • gb.File + gb.Directory to return both.

By specifying the pattern and filter appropriately, it is possible, for example, to search specifically for a single file or for a particular (subset) of all files in the specified base directory.

Example 1:

[1] Public Sub ScanDirectory()
[2]
[3]   Dim sDirectoryPath, sPattern, sDirFileName As String
[4]   Dim sFilter As Integer
[5]   Dim bMode, bSorted As Boolean
[6]
[7]   sDirectoryPath = User.Home &/ "BildTon"
[8]   sPattern = "[^0-9P]*.{png,jpg,gif}"
[9]   sFilter = gb.File  ' gb.Directory | gb.File + gb.Directory
[10]   bSorted = True
[11]   bMode = gb.Ascent  ' gb.Descent | gb.Ascent
[12]
[13]   If bSorted Then
[14]      If Dir(sDirectoryPath, sPattern, sFilter).Sort(bMode).Count = 0 Then
[15]         Message.Info("The searched set is empty ...")
[16]         Return
[17]      Else
[18]         For Each sDirFileName In Dir(sDirectoryPath, sPattern, sFilter).Sort(bMode)
[19]           Print sDirFileName
[20]         Next
[21]      Endif
[22]   Else
[23]      If Dir(sDirectoryPath, sPattern, sFilter).Count = 0 Then
[24]         Message.Info("The searched set is empty ...")
[25]         Return
[26]      Else
[27]         For Each sDirFileName In Dir(sDirectoryPath, sPattern, sFilter)
[28]           Print sDirFileName
[29]         Next
[30]      Endif
[31]   Endif
[32]
[33] End
[34]
[35] Public Sub btnScanDirectory_Click()
[36]   ScanDirectory()
[37] End

With the help of the procedure ScanDirectory(), you can have the set of search results output in the console after specifying the directory, the pattern, the filter, the sorting and the sorting order (lines 7 to 11).

The pattern in example 1 is chosen so that only files with the extension png, jpg and gif are in the result set - but their names do not begin with a digit from the set [0-7] or with a P. However, you can also process the results further in lines 19 and 28. It would be conceivable to store all paths of the (image) files of the result set in a string array.

In the following examples, the (base) directory, the pattern, the filter, the sorting and the sorting order are changed and the results are commented.

Example 2:

sDirectoryPath = User.Home
sPattern = "[^.]*.txt"
sFilter = gb.File
bSorted = False
bMode = gb.Ascent

Only non-hidden files with the extension .txt in the home directory are displayed. The result set is not sorted.

Example 3:

sDirectoryPath = User.Home
sPattern = ".[^A-Z]*"
sFilter = gb.Directory
bSorted = True
bMode = gb.Ascent

Only hidden directories in the home directory that do not begin with a capital letter are listed. The result set is sorted.

6.3.12 RDIR

ArrayOfFilenames = RDir ( BaseDirectory AS String [ , Pattern AS String , Filter AS Integer , FollowLink AS Boolean ] ) AS String[]

Returns a string array containing the names of the files and directories in the specified base directory and its subdirectories that match the pattern and filter. The notes on the pattern and filter for the DIR function apply. If the optional parameter FollowLink is TRUE, symbolic links to directories are followed. Otherwise they are processed like normal files.

Example:

[1] Public Sub ScanDirectoryR()
[2]
[3]   Dim sDirectoryPath, sPattern, sDirFileName As String
[4]   Dim sFilter As Integer
[5]   Dim bMode, bSorted As Boolean
[6]
[7]   sDirectoryPath = User.Home &/ "ImageSound"
[8]   sPattern = "*fractal_0.png"
[9]   sFilter = gb.File
[10]   bSorted = False
[11]   bMode = gb.Ascent
[12]
[13]   If bSorted Then
[14]      If RDir(sDirectoryPath, sPattern, sFilter).Sort(bMode).Count = 0 Then
[15]         Message.Info("The searched set is empty ...")
[16]         Return
[17]      Else
[18]         For Each sDirFileName In RDir(sDirectoryPath, sPattern, sFilter).Sort(bMode)
[19]           Print sDirFileName
[20]         Next
[21]      Endif
[22]   Else
[23]      If RDir(sDirectoryPath, sPattern, sFilter).Count = 0 Then
[24]         Message.Info("The searched set is empty ...")
[25]         Return
[26]      Else
[27]         For Each sDirFileName In RDir(sDirectoryPath, sPattern, sFilter)
[28]           Print sDirFileName
[29]         Next
[30]      Endif
[31]   Endif
[32]
[33] End
[34]
[35] Public Sub btnScanDirectoryR_Click()
[36]
[37]   ScanDirectoryR()
[38]
[39] End

The returned file paths are relative to the searched directory. However, the pattern always corresponds to the full relative path, not just the file name! This is not only reflected in the pattern sPattern = “*fractal_0.png”, but also in the result of the scan: Fractals/fractal_0.png with the specification of the applicable directory. The same applies to the recursive search in the directory tree: choose the pattern and the filter with care.

6.3.13 Excursus 1 - Determining the size of a directory

1st variant - shell instruction

Dim ilSourceSize As Long
Dim sSource, sResult, sProjectFolder As String
 
sProjectFolder = "GambasBookProjects"
sDestination = "/media/hans/DW_4GB" &/ sProjectFolder
sSource = User.Home &/ sProjectFolder
 
Exec ["du", "-sb", sSource] To sResult
 
ilSourceSize = CLong(Split(sResult, "\t")[0])
 
Print ilSourceSize

2nd variant

Public Function GetDirSize(sDir As String) As Long
 
' Coding and adaptation of Tony Morehen and Fabien Bodard
 
   Dim sFile As String
   Dim sPath As String
   Dim hStat As Stat
   Dim iSize As Long
 
   For Each sFile In Dir(sDir)
     sPath = sDir &/ sFile
     hStat = Stat(sPath)
     With hStat
       If .Type = gb.Directory Then
         iSize += GetDirSize(sPath) ' Recursion!
       Endif
       iSize += .Size
     End With
   Next
 
   Return iSize
 
End
 
Public Sub btnGetDirSize_Click()
 
  Dim ilDirSize As Long
 
  Try ilDirSize = GetDirSize(User.Home &/ "GambasBookProjects")
  If Error Then Message.Error(Error.Text)
  Print ilDirSize
 
End

6.3.14 Digression 2 - Create file

File.Save(sFilePath, "")
File.Save(sFilePath, sContent)

The statements create an empty file with the specified (absolute) file path sFilePath or a file with the content sContent. No error is raised if the file already exists, because then its content is overwritten!

Private Sub CreateTextFiles(sPathDir As String, iNumber As String)
 
  Dim sFileName As String
  Dim i As Integer
 
  For i = 1 To iNumber
    sFileName = Hex$(Rand(0, 2 ^ 32 - 1)) ' Random file name
    If Not Exist(sPathDir &/ sFileName & ".txt") Then
       File.Save(sPathDir &/ sFileName & ".txt", "Text line 1.\nText line 2.")
    Endif
  Next
End

The procedure CreateTextFiles(…) creates a given number (iNumber) of text files - with content - with the specified (absolute) file paths. The (base) file name is a random string.

6.3.15 Digression 3 - Copy Directory

The task is to copy a directory - with contents:

Public Sub CopyDir(Source As String, Destination As String)
 
  Dim sFile As String
 
  If IsDir(Source) Then
     If Not Exist(Destination) Then Mkdir Destination
     For Each sFile In Dir(Source)
       If Not Exist(Destination &/ sFile) Then
          CopyDir(Source &/ sFile, Destination &/ sFile) ' Recursion
          Wait
       Endif
     Next
  Else
     If Not Exist(Destination) Then
        Try Copy Source To Destination
        If Error Then Message.Error(Error.Text)
        Return
        Wait
     Endif
  Endif
 
End
 
Public Sub btnBackup_Click()
 
  CopyDir(User.Home &/ "GambasBookProjects", "/media/hans/DW_4GB" &/ "GambasBookProjects")
  Print "DONE!"
 
End
The website uses a temporary session cookie. This technically necessary cookie is deleted when the browser is closed. You can find information on cookies in our privacy policy.
k6/k6.3/start.txt · Last modified: 16.01.2022 (external edit)

Page Tools