The std::fs module provides multiple functions to interact with the file system. See Table 1.
Table 1:Some functions of the std::fs module
Function | Description |
|---|---|
| Copies the content of file |
| Creates a new folder. |
| Creates a new folder and all its parents if necessary. |
| Creates a new hard link |
| Reads the whole content of a file into a byte vector |
| Reads the whole content of a file into a |
| Deletes an empty folder. |
| Deletes a folder and all its content. |
| Deletes a file. |
| Renames a file or folder, overwriting any existing file at |
| Changes permissions of a file or directory. |
| Changes the timestamps of a file or directory. |
| Writes the content of |
36.3.1Writing a whole file¶
The write() function writes an entire string or byte string into a
file:
let content = "abcdef";
let file = std::path::Path::new("foo.txt");
std::fs::write(file, content)?;36.3.2Reading a whole file¶
The read_to_string() function reads a whole text file into a
String:
let content = std::fs::read_to_string(file)?;
content36.3.3Getting the size of a file¶
To obtain the size of a file, we need first to access the file’s
metadata and then call the len() method onto the
Metadata
object:
file.metadata()?.len()Checking if a file is empty is thus as easy as:
file.metadata()?.len() == 036.3.4Checking path existence¶
The exists() method of the Path struct tests the existence of a
path:
file.exists()36.3.5Testing file or folder¶
To test if a path is a file or a folder we use the is_file() and
is_dir() methods:
(file.is_file(), file.is_dir())36.3.6Creating a folder¶
The create_dir() function creates a new folder, at the condition
that the parent path exists:
std::fs::create_dir("my_folder")The create_dir_all() function creates a new folder, with all missing
parent folders:
std::fs::create_dir_all("my/other/folder")