← Back to lessons

35 Path

Hard

The fs package provides functions to parse and construct file paths in a way that is portable between operating systems (hopefully); dir/file on Linux vs. dir\file on Windows, for example.

For more functionality refer to: the official documentation.

Join should be used to construct paths in a portable way. First we call the constrcutor, then we chain the join calls to construct a hierarchical path from them.

The Path struct can operate on any of the following: //,/,\. For those confused, .. is a parent directory.

We also have a function that given a Path, returns Option<Path>, which includes all the directories in hierarchical order.

fileName, as name suggests, returns the name of the file at the end of the path.

We can check whether a path is absolute.

We can extract extension from a Path (we extract it from the filename to be exact). We can also get name without the extension at all.

Path.cj
import std.fs.*

main() {
    var path = Path("C:").join("Users").join("Isaac").join("options.cj")

    println("p: ${path}")

    println(Path("dir1//").join("filename.txt"))
    println(Path("dir/../dir1").join("filename"))

    println("Dir(p): ${path.directoryName}")

    println("Base(p): ${path.fileName}")

    println(Path("dir/file").isAbsolute())
    println(Path("/dir/file").isAbsolute())

    var file = Path("config.json")

    println(file.extensionName)
    println(file.fileNameWithoutExtension)
}

// Output:
// p: C:/Users/Isaac/options.cj
// dir1//filename.txt
// dir/../dir1/filename
// Dir(p): Some(C:/Users/Isaac)
// Base(p): Some(options.cj)
// false
// true
// Some(json)
// Some(config)