Skip to content

SpecificationXII · Library

12.7

Files and folders

To read or write files you ask for a folder capability, open the file with it, and every operation returns a Result that may carry an IoError.

Markdown version

12.7.1 How it works

The path is always the same:

  1. requestDirectory(path) gives a DirCap for that folder.
  2. folder.open(name, mode) gives a FileCap. With "lectura" it only reads; "escritura" creates or empties the file; "lectura_escritura" creates it if missing and keeps what it had.
  3. readText, writeText, appendText and their Bytes versions 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.

Figure 12.7-1.From folder to file and from file to contents. Every arrow is an operation that may fail with an 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
EndAlgorithm

Output

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
EndAlgorithm

Output

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 IoError inside a Result.
  • Propagate returns the error to the caller.