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:
- Paths: taking paths apart and putting them together.
- Reading and writing files: a whole file in one call.
- Line by line:
File,TextWriterandReadLines. - Text encodings: UTF-16, Windows code pages and raw bytes.
- Opening a File: the ways to open, and what each refuses.
- Records at a position:
RecordFile,ReadAtandWriteAt. - Binary formats: numbers in a byte order, and varints.
- Streams: one interface for files, memory and your own types.
- File information:
Statand the yes-or-no questions. - Directories: creating, walking and removing trees.
- Where files live: the configuration, data and cache directories, and the program's own path.
- Checksums and hashes: CRC-32, SHA-256 and HMAC.
- TOML settings: reading a configuration file with types.
- INI files: sections of
key = value, read and written.
Activities
- Write a second file into the scratch directory and check that the count
RemoveDirAllprints goes up by one. - Print
missing.Failure( ).Message( )to see the error as text.