BlitzMax/Modules/System/File system

From Wikibooks, open books for an open world
Jump to: navigation, search

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.

Functions[edit]

StripDir[edit]

Function StripDir$( path$ )

Description: Strip directory from a file path

Example:

' stripdir.bmx

print stripdir("mypath/myfile.bmx")   'prints myfile.bmx

StripExt[edit]

Function StripExt$( path$ )

Description: Strip extension from a file path

Example:

' stripext.bmx

print stripext("mypath/myfile.bmx")   'prints mypath/myfile

StripAll[edit]

Function StripAll$( path$ )

Description: Strip directory and extension from a file path

Example:

' stripall.bmx

print stripall("mypath/myfile.bmx")   'prints myfile

StripSlash[edit]

Function StripSlash$( path$ )

Description: Strip trailing slash from a file path

Information: StripSlash will not remove the trailing slash from a 'root' path. For example, "/" or (on Win32 only) "C:/".

Example:

' stripslash.bmx

print stripslash("mypath/")   'prints mypath

ExtractDir[edit]

Function ExtractDir$( path$ )

Description: Extract directory from a file path

Example:

' extractdir.bmx

print extractdir("mypath/myfile.bmx") 'prints mypath

ExtractExt[edit]

Function ExtractExt$( path$ )

Description: Extract extension from a file path

Example:

' extractext.bmx

print extractext("mypath/myfile.bmx") 'prints bmx

CurrentDir[edit]

Function CurrentDir$()

Description: Get Current Directory

Returns: The current directory

Example:

' currentdir.bmx

cd$=currentdir()
print "CurrentDir()="+cd$

RealPath[edit]

Function RealPath$( path$ )

Description: Get real, absolute path of a file path

Example:

' realpath.bmx

print realpath("realpath.bmx")        'prints full path of this source

print realpath("..") 'prints full path of parent directory

FileType[edit]

Function FileType( path$ )

Description: Get 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

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

FileTime[edit]

Function FileTime( path$ )

Description: Get file time

Returns: The time the file at path was last modified

Example:

' filetime.bmx

print filetime("filetime.bmx")

FileSize[edit]

Function FileSize( path$ )

Description: Get file size

Returns: Size, in bytes, of the file at path, or -1 if the file does not exist

Example:

' filesize.bmx

' the following prints the size of this source file in bytes

print filesize("filesize.bmx")

FileMode[edit]

Function FileMode( path$ )

Description: Get file mode

Returns: file mode flags

Example:

' filemode.bmx

' the following function converts the file mode to 
' the standard unix permission bits string

Function Permissions$(mode)
        local   testbit,pos
        local   p$="rwxrwxrwx"
        testbit=%100000000
        pos=1
        while (testbit)
                if mode & testbit res$:+mid$(p$,pos,1) else res$:+"-"
                testbit=testbit shr 1
                pos:+1  
        wend
        return res
End Function

print Permissions$(filemode("filemode.bmx"))

SetFileMode[edit]

Function SetFileMode( path$,mode )

Description: Set file mode

Example:

' setfilemode.bmx

' the following makes this source file readonly

writebits=%010010010

' read the file mode

mode=filemode("setfilemode.bmx")

'mask out the write bits to make readonly

mode=mode & ~writebits

'set the new file mode

setfilemode("setfilemode.bmx",mode)   

CreateFile[edit]

Function CreateFile( path$ )

Description: Create a file

Returns: True if successful

Example:

' createfile.bmx

success=createfile("myfile")
if not success runtimeerror "error creating file"

CreateDir[edit]

Function CreateDir( path$,recurse=False )

Description: Create a directory

Returns: True if successful

Information: If recurse is true, any required subdirectories are also created.

Example:

' createdir.bmx

success=createdir("myfolder")
if not success runtimeerror "error creating directory"

DeleteFile[edit]

Function DeleteFile( path$ )

Description: Delete a file

Returns: True if successful

Example:

' deletefile.bmx

success=deletefile("myfile")
if not success runtimeerror "error deleting file"

RenameFile[edit]

Function RenameFile( oldpath$,newpath$ )

Description: Renames a file

Returns: True if successful

CopyFile[edit]

Function CopyFile( src$,dst$ )

Description: Copy a file

Returns: True if successful

CopyDir[edit]

Function CopyDir( src$,dst$ )

Description: Copy a directory

Returns: True if successful

DeleteDir[edit]

Function DeleteDir( path$,recurse=False )

Description: Delete a directory

Returns: True if successful

Information: Set recurse to true to delete all subdirectories and files recursively - but be careful!

Example:

' deletedir.bmx

success=deletedir("myfolder")
if not success runtimeerror "error deleting directory"

ChangeDir[edit]

Function ChangeDir( path$ )

Description: Change current directory

Returns: True if successful

Example:

' changedir.bmx

print "CurrentDir()="+currentdir()

' change current folder to the parent folder

changedir ".."

' print new CurrentDir()

print "CurrentDir()="+currentdir()

ReadDir[edit]

Function ReadDir( path$ )

Description: Open a directory

Returns: An integer directory handle, or 0 if the directory does not exist

Example:

' readdir.bmx

dir=ReadDir(CurrentDir())

If Not dir RuntimeError "failed to read current directory"

Repeat
        t$=NextFile( dir )
        If t="" Exit
        If t="." Or t=".." Continue
        Print t 
Forever

CloseDir dir

NextFile[edit]

Function NextFile$( dir )

Description: Return next file in a directory

Returns: File name of next file in directory opened using ReadDir, or an empty string if there are no more files to read.

CloseDir[edit]

Function CloseDir( dir )

Description: Close a directory

LoadDir[edit]

Function LoadDir$[]( dir$,skip_dots=True )

Description: Load a directory

Returns: A string array containing contents of dir

Information: The skip_dots parameter, if true, removes the '.' (current) and '..' (parent) directories from the returned array.

Example:

' loaddir.bmx

' declare a string array

local files$[]

files=loaddir(currentdir())

for t$=eachin files
        print t 
next

OpenFile[edit]

Function OpenFile:TStream( url:Object,readable=True,writeable=True )

Description: Open a file for input and/or output.

Information: 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

' the following prints the contents of this source file 

file=openfile("openfile.bmx")

if not file runtimeerror "could not open file openfile.bmx"

while not eof(file)
        print readline(file)
wend
closestream file

ReadFile[edit]

Function ReadFile:TStream( url:Object )

Description: Open a file for input.

Information: 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 

file=readfile("readfile.bmx")

if not file runtimeerror "could not open file openfile.bmx"

while not eof(file)
        print readline(file)
wend

closestream file

WriteFile[edit]

Function WriteFile:TStream( url:Object )

Description: Open a file for output.

Information: This command is identical to the WriteStream command.

Example:

' writefile.bmx

file=writefile("test.txt")

if not file runtimeerror "failed to open test.txt file" 

writeline file,"hello world"

closestream file

CloseFile[edit]

Function CloseFile( stream:TStream )

Description: Closes a file stream.

Information: After performing file operations on an open file make sure to close the file stream with either CloseFile or the identical CloseStream command.