Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Files

Files are the std/fs module. It opens and closes files, reads and writes them whole or a line at a time, takes paths apart, walks directories and says where a program should keep its own files. Every operation that can fail returns a Result: a missing file is a value you look at, not a crash.

#import "std/fs"

print "Files"
'' A scratch directory of our own, under a fresh name.
dim as ustring dir_ = fs.CreateTempDir( "tbe" ).Value( )
dim as ustring p = fs.PathJoin( dir_, "greeting.txt" )

fs.WriteAllText( p, "hello, file" )
print fs.ReadAllText( p ).Value( )

var info = fs.Stat( p )
print "size:"; info.Value( ).Size( ); ", file: "; info.Value( ).IsFile( )

'' A failure is a value to look at, not a crash.
var missing = fs.ReadAllText( fs.PathJoin( dir_, "nope.txt" ) )
print "read a missing file: "; missing.IsOk( )
print "not found: "; cbool( missing.Failure( ).Code( ) = fs.FS_NOT_FOUND )

print "removed:"; fs.RemoveDirAll( dir_ ).Value( )

Output

Files
hello, file
size:11, file: true
read a missing file: false
not found: true
removed: 2

CreateTempDir makes a directory under a fresh, unpredictable name, which the examples in this section use so that they never touch anything else. PathJoin builds a path with the platform's separator. WriteAllText and ReadAllText write and read a whole file as text, and Stat gathers the facts about a file in one call.

ReadAllText of a file that is not there returns a failure instead of a value. IsOk( ) says which you have, Value( ) is the value, and Failure( ) is an FsError whose Code( ) says what went wrong. Value( ) on a failure is a runtime error, so test first when failure is possible. RemoveDirAll deletes a whole tree and returns how many objects it removed.

The pages in this section:

Activities

  1. Write a second file into the scratch directory and check that the count RemoveDirAll prints goes up by one.
  2. Print missing.Failure( ).Message( ) to see the error as text.