LEVIATHAN v962456e · 962456eee1

Standard Library

interface IFileSystem

What a program may do with the file system: open files and check whether a path exists.

since 0.1.0-alpha.1linuxwindowswasm

Overview

A function that takes an IFileSystem parameter does not touch the real disk directly, so a test can pass an implementation backed by memory. use std::IFileSystem; makes the real file system (SystemFileSystem) the default for such parameters.

Examples

class MemoryFs : IFileSystem {
    File open(string path, OpenMode mode) {
        throw FileException("read-only test file system: " + path);
    }
    bool exists(string path) => path == "/config.txt";
}

void check(IFileSystem fs) {
    console.writeln(fs.exists("/config.txt"));
    console.writeln(fs.exists("/other.txt"));
    try {
        fs.open("/config.txt", std::read);
    } catch (FileException e) {
        console.writeln(e.message);
    }
}

bind IFileSystem => MemoryFs();
check();
true
false
read-only test file system: /config.txt

Methods

exists

exists(string path) -> bool

Check whether a path exists.

Parameters

path
The path to look up.

Returns

true when something exists at the path.

Examples

class OneFile : IFileSystem {
    File open(string path, OpenMode mode) {
        throw FileException("not supported");
    }
    bool exists(string path) => path == "/only.txt";
}
IFileSystem fs = OneFile();
console.writeln(fs.exists("/only.txt"));
console.writeln(fs.exists("/missing.txt"));
true
false

open

open(string path, OpenMode mode) -> File

Open a file.

Parameters

path
The path of the file.
mode
How to open it, such as std::read or std::write.

Returns

The opened file.

Throws

FileException
when the file cannot be opened.

Examples

class NoFiles : IFileSystem {
    File open(string path, OpenMode mode) {
        throw FileException("no such file: " + path);
    }
    bool exists(string path) => false;
}
IFileSystem fs = NoFiles();
try {
    fs.open("/data.txt", std::read);
} catch (FileException e) {
    console.writeln(e.message);
}
no such file: /data.txt

See also

  • SystemFileSystem — The real file system behind the IFileSystem interface.
  • File — An open file.