BRL.FileSystem
The BlitzMax filesystem module contains commands to perform operations on the computer's files and directories.
OpenFile, ReadFile and WriteFile return a stream object for reading and or writing data to files.
Directories can be examined file by file using a combination of the ReadDir, NextFile and CloseDir commands, or LoadDir can be used to read the file names of a directory into a string array.
File properties can be examined with the FileType, FileTime, FileSize and FileMode commands.
Files and directories (folders) can be created and deleted with the CreateFile, CreateDir DeleteFile and DeleteDir commands.
Finally, the FileSystem module contains various utility functions for handling file paths in a system independent manner. These commands include RealPath, StripDir, StripExt, StripAll, ExtractDir and ExtractExt.
File Walking
The filesystem module also provides a file walking API for recursively traversing directory trees.
File walking is performed using the WalkFileTree function, which starts at a given path and visits each file and directory in turn. Instead of returning results directly, WalkFileTree calls back into a user-supplied object that implements the IFileWalker interface.
To use file walking, create a type that implements IFileWalker and provide an implementation of the WalkFile method. This method is called once for every file and directory encountered during the walk and is passed an SFileAttributes structure containing information about the current entry.
The SFileAttributes structure provides access to the file or directory name, size, timestamps, type information (regular file, directory or symbolic link), and the current depth within the directory tree.
The return value of WalkFile controls how the traversal proceeds. Returning EFileWalkResult.OK continues normally. Returning EFileWalkResult.SkipSubtree skips descending into the current directory, while EFileWalkResult.SkipSiblings skips remaining entries at the current level. Returning EFileWalkResult.Terminate immediately stops the walk.
Traversal behavior can be configured using the EFileWalkOption flags passed to WalkFileTree. For example, the EFileWalkOption.FollowLinks option enables traversal of symbolic links. The maximum recursion depth can also be limited.
Example
The following example shows a simple file walker that prints the name of each file and directory encountered:
Type TPrintWalker Implements IFileWalker
Method WalkFile:EFileWalkResult(attributes:SFileAttributes Var)
Print attributes.GetName()
Return EFileWalkResult.OK
End Method
End Type
Local walker:IFileWalker = New TPrintWalker
WalkFileTree(“mydirectory”, walker)
More complex walkers can use the information in SFileAttributes to filter files, collect statistics, or selectively control traversal.
Related APIs
File walking is intended for recursive and event-driven traversal of directory trees. For non-recursive directory access, the ReadDir, NextFile and CloseDir commands, or the LoadDir function, may be more appropriate.
Interfaces
| Interface | Description |
|---|---|
| IFileWalker | An interface for file tree traversal. |
Structs
| Struct | Description |
|---|---|
| SFileAttributes | File attributes |
Enums
| Enum | Description |
|---|---|
| EFileWalkOption | File walk options |
| EFileWalkResult | File walk result codes returned by the IFileWalker |
Functions
Function StripDir:String( path:String )
Strips the directory from a file path
Example
' stripdir.bmx
SuperStrict
Print StripDir("mypath/myfile.bmx") ' prints myfile.bmx
Function StripExt:String( path:String )
Strips the extension from a file path
Example
' stripext.bmx
SuperStrict
Print StripExt("mypath/myfile.bmx") ' prints mypath/myfile
Function StripAll:String( path:String )
Strips the directory and extension from a file path
Example
' stripall.bmx
SuperStrict
Print StripAll("mypath/myfile.bmx") ' prints myfile
Function StripSlash:String( path:String )
Strips trailing slash from a file path
StripSlash will not remove the trailing slash from a 'root' path. For example, "/" or (on Win32 only) "C:/".
Example
' stripslash.bmx
SuperStrict
Print StripSlash("mypath/") ' prints mypath
Function ExtractDir:String( path:String )
Extracts the directory from a file path
Example
' extractdir.bmx
SuperStrict
Print ExtractDir("mypath/myfile.bmx") ' prints mypath
Function ExtractExt:String( path:String )
Extracts the extension from a file path
Example
' extractext.bmx
SuperStrict
Print ExtractExt("mypath/myfile.bmx") ' prints bmx
Function CurrentDir:String()
Gets the Current Directory
Returns
The current directory
Example
' currentdir.bmx
SuperStrict
Local cd:String = CurrentDir()
Print "CurrentDir()="+cd
Function RealPath:String( path:String )
Gets the real, absolute path of a file path
Example
' realpath.bmx
SuperStrict
Print RealPath("realpath.bmx") 'prints full path of this source
Print RealPath("..") 'prints full path of parent directory
Function FileType:Int( path:String )
Gets the file type
Returns
0 if file at path doesn't exist, FILETYPE_FILE (1) if the file is a plain file or FILETYPE_DIR (2) if the file is a directory
Example
' filetype.bmx
SuperStrict
Print FileType(".") ' prints 2 for directory type
Print FileType("filetype.bmx") ' prints 1 for file type
Print FileType("notfound.file") ' prints 0 for doesn't exist
Function FileExists:Int( path:String )
Checks if a file or directory exists
Use FileType to check if the file is a directory or a plain file.
Returns
True if the file or directory at path exists
Function FileTime:Long( path:String, timetype:Int=FILETIME_MODIFIED )
Gets file time
Returns
The time the file at path was last modified.
Example
' filetime.bmx
SuperStrict
Print FileTime("filetime.bmx")
Function SetFileTime( path:String, time:Long, timeType:Int=FILETIME_MODIFIED)
Sets the file modified or last accessed time.
time should be number of seconds since epoch.
Example
' setfiletime.bmx
SuperStrict
Const FILENAME:String = "file.txt"
SaveString("Hello", FILENAME)
Local ft:Long = FileTime(FILENAME)
Print ft
ft :- 3600 ' less 1 hour
SetFileTime(FILENAME, ft)
Print FileTime(FILENAME)
Function SetFileTime( path:String, dateTime:SDateTime, timeType:Int=FILETIME_MODIFIED)
Sets the file modified or last accessed time.
dateTime is the basic DateTime struct defined in pub.stdc .
Example
' setfiletime.bmx
SuperStrict
Const FILENAME:String = "file.txt"
SaveString("Hello", FILENAME)
Local ft:Long = FileTime(FILENAME)
Print ft
ft :- 3600 ' less 1 hour
SetFileTime(FILENAME, ft)
Print FileTime(FILENAME)
Function FileDateTime:SDateTime( path:String, timetype:Int=FILETIME_MODIFIED )
Gets file time
Returns
The time the file at path was last modified as SDatetime struct.
Function SetFileDateTime( path:String, dateTime:SDateTime, timeType:Int=FILETIME_MODIFIED)
Sets the file modified or last accessed time.
dateTime is the basic DateTime struct defined in pub.stdc .
Function FileSize:Long( path:String )
Gets the file size
Returns
The size, in bytes, of the file at path, or -1 if the file does not exist
Example
' filesize.bmx
SuperStrict
' the following prints the size of this source file in bytes
Print FileSize("filesize.bmx")
Function FileMode:Int( path:String )
Gets the file mode
Returns
The file mode flags
Example
' filemode.bmx
SuperStrict
' the following function converts the file mode to
' the standard unix permission bits string
Function Permissions:String(mode:Int)
Local testbit:Int, pos:Int
Local p:String = "rwxrwxrwx"
testbit = %100000000
pos = 1
Local res:String
While (testbit)
If mode & testbit
res :+ Mid(p, pos, 1)
Else
res :+ "-"
EndIf
testbit = testbit Shr 1
pos :+ 1
Wend
Return res
End Function
Print Permissions(FileMode("filemode.bmx"))
Function SetFileMode( path:String,Mode:Int )
Sets file mode
Example
' setfilemode.bmx
SuperStrict
' the following makes this source file readonly
Local writebits:Int = %010010010
' read the file mode
Local mode:Int = FileMode("setfilemode.bmx")
'mask out the write bits to make readonly
mode = mode & ~writebits
'set the new file mode
SetFileMode("setfilemode.bmx",mode)
Function CreateFile:Int( path:String )
Creates a file
Returns
True if successful
Example
' createfile.bmx
SuperStrict
Local success:Int = CreateFile("myfile")
If Not success Then
RuntimeError "error creating file"
End If
Function CreateDir:Int( path:String,recurse:Int=False )
Creates a directory
If recurse is True, any required subdirectories are also created.
Returns
True if successful
Example
' createdir.bmx
SuperStrict
Local success:Int = CreateDir("myfolder")
If Not success Then
RuntimeError "error creating directory"
End If
Function DeleteFile:Int( path:String )
Deletes a file
Returns
True if successful
Example
' deletefile.bmx
SuperStrict
Local success:Int = DeleteFile("myfile")
If Not success RuntimeError "error deleting file"
Function RenameFile:Int( oldpath:String,newpath:String )
Renames a file
Returns
True if successful
Example
SuperStrict
Local result:Int = CopyFile(BlitzMaxPath() + "\versions.txt", BlitzMaxPath() + "\versions2.txt")
If result = 0 Then
RuntimeError "CopyFile not successful..."
End If
result = RenameFile(BlitzMaxPath() + "\versions.txt", BlitzMaxPath() + "\versions2.txt")
If result = 0 Then
RuntimeError "Rename not successful..." ' as file already exist
End If
Function CopyFile:Int( src:String,dst:String )
Copies a file
Returns
True if successful
Example
SuperStrict
Local result:Int = CopyFile(BlitzMaxPath() + "\versions.txt", BlitzMaxPath() + "\versions2.txt")
If result = 0 Then
RuntimeError "CopyFile not successful..."
End If
result = RenameFile(BlitzMaxPath() + "\versions.txt", BlitzMaxPath() + "\versions2.txt")
If result = 0 Then
RuntimeError "Rename not successful..." ' as file already exists
End If
Function CopyDir:Int( src:String,dst:String )
Copies a directory
Returns
True if successful
Function DeleteDir:Int( path:String,recurse:Int=False )
Deletes a directory
Set recurse to True to delete all subdirectories and files recursively - but be careful!
Returns
True if successful
Example
' deletedir.bmx
SuperStrict
Local success:Int = DeleteDir("myfolder")
If Not success Then
RuntimeError "error deleting directory"
End If
Function ChangeDir:Int( path:String )
Changes the current directory
Returns
True if successful
Example
' changedir.bmx
SuperStrict
Print "CurrentDir()="+CurrentDir()
' change current folder to the parent folder
ChangeDir ".."
' print new CurrentDir()
Print "CurrentDir()="+CurrentDir()
Function ReadDir:Byte Ptr( path:String )
Opens a directory
Use NextFile to get the next file in the directory. The directory must be closed with CloseDir.
Returns
A directory handle, or Null if the directory does not exist
Example
' readdir.bmx
SuperStrict
Local dir:Byte Ptr = ReadDir(CurrentDir())
If Not dir RuntimeError "failed to read current directory"
Repeat
Local t:String = NextFile( dir )
If t="" Exit
If t="." Or t=".." Continue
Print t
Forever
CloseDir dir
Function NextFile:String( dir:Byte Ptr )
Returns the next file in a directory
Returns
File name of next file in the directory opened using ReadDir, or an empty String if there are no more files to read.
Example
'File System Example
SuperStrict
Local dir:Byte Ptr = ReadDir(BlitzMaxPath() )
If Not dir Then
RuntimeError "Cannot open folder"
End If
Local file:String
Repeat
file = NextFile(Dir) ' Get the filenames in folder
Print file
Until file = ""
CloseDir(dir)
Function CloseDir( dir:Byte Ptr )
Closes a directory.
Closes a directory opened with ReadDir.
Example
'File System Example
SuperStrict
Local dir:Byte Ptr = ReadDir(BlitzMaxPath())
If Not dir Then
RuntimeError "Cannot open folder"
End If
Local file:String
Repeat
file = NextFile(dir) ' Get the filenames in folder
Print file
Until Not file
CloseDir(dir)
Function LoadDir:String[]( dir:String,skip_dots:Int=True )
Loads a directory
The skip_dots parameter, if true, removes the '.' (current) and '..' (parent) directories from the returned array.
Returns
A string array containing contents of dir
Example
' loaddir.bmx
SuperStrict
' declare a string array
Local files:String[]
files = LoadDir(CurrentDir())
For Local t:String = EachIn files
Print t
Next
Function OpenFile:TStream( url:Object,readable:Int=True,writeable:Int=True )
Opens a file for input and/or output.
This command is similar to the OpenStream command but will attempt to cache the contents of the file to ensure serial streams such as http: based url's are seekable. Use the CloseStream command when finished reading and or writing to a Stream returned by OpenFile.
Example
' openfile.bmx
SuperStrict
' the following prints the contents of this source file
Local file:TStream = OpenFile("openfile.bmx")
If Not file RuntimeError "could not open file openfile.bmx"
While Not Eof(file)
Print ReadLine(file)
Wend
CloseStream file
Function ReadFile:TStream( url:Object )
Opens a file For Input.
This command is similar to the ReadStream command but will attempt to cache the contents of the file to ensure serial streams such as http: based url's are seekable. Use the CloseStream command when finished reading and or writing to a Stream returned by OpenFile.
Example
' readfile.bmx
' the following prints the contents of this source file
SuperStrict
Local file:TStream = ReadFile("readfile.bmx")
If Not file RuntimeError "could not open file openfile.bmx"
While Not Eof(file)
Print ReadLine(file)
Wend
CloseStream file
Function WriteFile:TStream( url:Object )
Opens a file for output.
This command is identical to the WriteStream command.
Example
' writefile.bmx
SuperStrict
Local file:TStream = WriteFile("test.txt")
If Not file Then RuntimeError "failed to open test.txt file"
WriteLine file,"hello world"
CloseStream file
Function CloseFile( stream:TStream )
Closes a file stream.
After performing file operations on an open file make sure to close the file stream with either CloseFile or the identical CloseStream command.
Example
SuperStrict
Local in:TStream = OpenFile(BlitzMaxPath() + "\versions.txt")
Local line:String
While Not Eof(in)
line = ReadLine(in)
Print line
Wend
CloseFile(in) ' can also use CloseStream(in)
Function WalkFileTree:Int(path:String, fileWalker:IFileWalker, options:EFileWalkOption = EFileWalkOption.None, maxDepth:Int = 0)
Walks a file tree.
Traverses the file tree starting at path, calling the IFileWalker interface for each file and directory found.
The options parameter can be used to modify the behaviour of the file tree walker. See EFileWalkOption for available options.
The maxDepth parameter can be used to limit how deep into the file tree the walker will traverse. A maxDepth of 0 (the default) means there is no limit to the depth of traversal.
The IFileWalker interface's WalkFile method is called for each file and directory found, and should return one of the EFileWalkResult values to control the traversal.
