Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

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

copy(p, q)

Copies the content of file p into q.

create_dir(p)

Creates a new folder.

create_dir_all(p)

Creates a new folder and all its parents if necessary.

hard_link(p, q)

Creates a new hard link q for p.

read(p)

Reads the whole content of a file into a byte vector Vec<u8>.

read_to_string(p)

Reads the whole content of a file into a String.

remove_dir(p)

Deletes an empty folder.

remove_dir_all(p)

Deletes a folder and all its content.

remove_file(p)

Deletes a file.

rename(p, q)

Renames a file or folder, overwriting any existing file at q.

set_permissions(p, perm)

Changes permissions of a file or directory.

set_times(p, times)

Changes the timestamps of a file or directory.

write(p, s)

Writes the content of s into the file at p. The file is created if it does not exist, and overwritten otherwise. s can be a regular string slice or a byte slice.

36.3.1Writing a whole file

The write() function writes an entire string or byte string into a file:

36.3.2Reading a whole file

The read_to_string() function reads a whole text file into a String:

36.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:

Checking if a file is empty is thus as easy as:

36.3.4Checking path existence

The exists() method of the Path struct tests the existence of a path:

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:

36.3.6Creating a folder

The create_dir() function creates a new folder, at the condition that the parent path exists:

The create_dir_all() function creates a new folder, with all missing parent folders: