Copying Files
Copying files is a frequent requirement for tasks such as backups or duplicating data. Rust’sfs::copy function makes this process straightforward.
The example below copies the contents of “example.txt” to “example_copy.txt” and prints a confirmation message upon success:
Moving and Renaming Files
Renaming or relocating files is another common operation. Rust’sfs::rename function serves both purposes, whether you need to rename a file or move it to a different directory.
For example, to rename “example_copy.txt” to “renamed_example.txt”:
Deleting Files
For removing files that are no longer necessary, Rust provides thefs::remove_file function.
The following example demonstrates how to delete a file:
Be cautious when deleting files since removed files cannot be recovered using the Rust standard library.
Directory Operations
Rust offers comprehensive support for working with directories, including operations to create, read, and remove directories.Creating a Directory
You can create a new directory using thefs::create_dir function:
Reading Directory Contents
To list the contents of a directory, use thefs::read_dir function. This function returns an iterator over directory entries. The example below prints the names of all entries in the current directory:
Removing Directories
Rust provides two distinct functions for directory removal:fs::remove_dirto remove empty directories.fs::remove_dir_allto remove directories along with all their contents.
Summary
In this tutorial, we reviewed several key filesystem operations in Rust:| Operation | Description | Function Reference |
|---|---|---|
| Copying Files | Duplicating file contents to a new file | fs::copy |
| Moving/Renaming Files | Renaming or moving files between directories | fs::rename |
| Deleting Files | Removing unnecessary files from the filesystem | fs::remove_file |
| Creating Directories | Generating new directories | fs::create_dir |
| Reading Directory Contents | Listing files and folders within a directory | fs::read_dir |
| Removing Directories | Deleting directories, including non-empty ones | fs::remove_dir_all |
This guide covers essential file and directory manipulation techniques in Rust, including copying, moving, renaming, and deleting operations. Always ensure to handle errors appropriately when working with file systems, and be mindful of concurrency control for performance-critical applications.
