axstd/fs/
mod.rs

1//! Filesystem manipulation operations.
2
3mod dir;
4mod file;
5
6use crate::io::{self, prelude::*};
7
8#[cfg(feature = "alloc")]
9use alloc::{string::String, vec::Vec};
10
11pub use self::dir::{DirBuilder, DirEntry, ReadDir};
12pub use self::file::{File, FileType, Metadata, OpenOptions, Permissions};
13
14/// Read the entire contents of a file into a bytes vector.
15#[cfg(feature = "alloc")]
16pub fn read(path: &str) -> io::Result<Vec<u8>> {
17    let mut file = File::open(path)?;
18    let size = file.metadata().map(|m| m.len()).unwrap_or(0);
19    let mut bytes = Vec::with_capacity(size as usize);
20    file.read_to_end(&mut bytes)?;
21    Ok(bytes)
22}
23
24/// Read the entire contents of a file into a string.
25#[cfg(feature = "alloc")]
26pub fn read_to_string(path: &str) -> io::Result<String> {
27    let mut file = File::open(path)?;
28    let size = file.metadata().map(|m| m.len()).unwrap_or(0);
29    let mut string = String::with_capacity(size as usize);
30    file.read_to_string(&mut string)?;
31    Ok(string)
32}
33
34/// Write a slice as the entire contents of a file.
35pub fn write<C: AsRef<[u8]>>(path: &str, contents: C) -> io::Result<()> {
36    File::create(path)?.write_all(contents.as_ref())
37}
38
39/// Given a path, query the file system to get information about a file,
40/// directory, etc.
41pub fn metadata(path: &str) -> io::Result<Metadata> {
42    File::open(path)?.metadata()
43}
44
45/// Returns an iterator over the entries within a directory.
46pub fn read_dir(path: &str) -> io::Result<ReadDir> {
47    ReadDir::new(path)
48}
49
50/// Creates a new, empty directory at the provided path.
51pub fn create_dir(path: &str) -> io::Result<()> {
52    DirBuilder::new().create(path)
53}
54
55/// Recursively create a directory and all of its parent components if they
56/// are missing.
57pub fn create_dir_all(path: &str) -> io::Result<()> {
58    DirBuilder::new().recursive(true).create(path)
59}
60
61/// Removes an empty directory.
62pub fn remove_dir(path: &str) -> io::Result<()> {
63    arceos_api::fs::ax_remove_dir(path)
64}
65
66/// Removes a file from the filesystem.
67pub fn remove_file(path: &str) -> io::Result<()> {
68    arceos_api::fs::ax_remove_file(path)
69}
70
71/// Rename a file or directory to a new name.
72/// Delete the original file if `old` already exists.
73///
74/// This only works then the new path is in the same mounted fs.
75pub fn rename(old: &str, new: &str) -> io::Result<()> {
76    arceos_api::fs::ax_rename(old, new)
77}