Rust filesystem

From wikinotes
Revision as of 01:27, 9 February 2023 by Will (talk | contribs) (→‎Filepaths)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

Documentation

std::fs https://doc.rust-lang.org/std/fs/index.html
std::path https://doc.rust-lang.org/std/path/index.html
std::env https://doc.rust-lang.org/std/env/index.html

Locations

std::env::home_dir()        // get user's home directory

Filesystem

Some common filesystem operations

use std::fs;
use std::env;
use std::os::unix::fs;

std::os::unix::fs::chown()  // chown
std::fs::set_permissions()  // chmod
std::env::current_dir()     // cwd/pwd

std::fs::copy()            // copy file to another

std::fs::soft_link()       // create symlink
std::fs::rename()          // rename/move a file
std::fs::create_dir()      // mkdir
std::fs::create_dir_all()  // mkdir -p

std::fs::read_dir()        // list dirs/files in dir (non-recursive)

std::fs::remove_dir        // remove empty dir
std::fs::remove_dir_all()  // remove files from dir, then dir (recursive?)
std::fs::remove_file()      // remove a file

Filepaths

path parsing

use std::path::Path;

let path = Path::new("/var/tmp/foo.txt");
path.parent()    // '/var/tmp'
path.extension() // 'txt'

path building

let path = PathBuf::from("/var");
path.push("tmp");
path.push("foo");
path.set_extension("txt")

Files

Temporary Files/Directories