Rust filesystem: Difference between revisions
From wikinotes
Line 48: | Line 48: | ||
= Filepaths = | = Filepaths = | ||
<blockquote> | <blockquote> | ||
path parsing | |||
<syntaxhighlight lang="rust"> | |||
use std::path::Path; | |||
let path = Path::new("/var/tmp/foo.txt"); | |||
path.parent() // '/var/tmp' | |||
path.extension() // 'txt' | |||
</syntaxhighlight> | |||
path building | |||
<syntaxhighlight lang="rust"> | |||
let path = PathBuf::from("/var"); | |||
path.push("tmp"); | |||
path.push("foo"); | |||
path.set_extension("txt") | |||
</syntaxhighlight> | |||
</blockquote><!-- Filepaths --> | </blockquote><!-- Filepaths --> | ||
Latest revision as of 01:27, 9 February 2023
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")