12.7.1 How it works
The path is always the same:
requestDirectory(path)gives aDirCapfor that folder.folder.open(name, mode)gives aFileCap. With"lectura"it only reads;"escritura"creates or empties the file;"lectura_escritura"creates it if missing and keeps what it had.readText,writeText,appendTextand theirBytesversions do the work.
Every step can fail, so it returns Result<…, IoError>. With Propagate, a failure is returned to the caller without writing the Switch by hand.
IoError.DirCap leads with open to FileCap, which leads with readText to the contents "Comprar pan". Every step can end in Error(IoError).
ProgramSaving and re-reading a note
Subroutine GuardarNota() As Result<String, IoError>
Define carpeta As DirCap <- Propagate requestDirectory(".");
Define archivo As FileCap <- Propagate carpeta.open("nota.txt", "escritura");
Define cantidad As Integer <- Propagate archivo.writeText("Comprar pan");
Write "Bytes: ", cantidad;
Define lector As FileCap <- Propagate carpeta.open("nota.txt", "lectura");
Return lector.readText();
EndSubroutine
Algorithm Notas
Switch GuardarNota() Do
Success(texto): Write texto;
Failure(problema): Write problema.code;
EndSwitch
EndAlgorithmOutput
Bytes: 11 Comprar pan
The program finishes normally.
A file that does not exist does not stop the program: it arrives as an Error whose code is "no_encontrado", and the program decides what to do.
ProgramA file that is not there
Subroutine LeerConfig() As Result<String, IoError>
Define carpeta As DirCap <- Propagate requestDirectory(".");
Define archivo As FileCap <- Propagate carpeta.open("config.txt", "lectura");
Return archivo.readText();
EndSubroutine
Algorithm Config
Switch LeerConfig() Do
Success(texto): Write texto;
Failure(problema): Write "No se pudo leer: ", problema.code;
EndSwitch
EndAlgorithmOutput
No se pudo leer: no_encontrado
The program finishes normally.
Folders can also be queried and changed: exists, isDirectory, list (sorted), createDirectory, rename and delete (never recursive). subdirectory gives a confined capability that cannot leave its folder.
In short
- Folder, file and contents: three steps, each one fallible.
- Failures arrive as
IoErrorinside aResult. Propagatereturns the error to the caller.