DEV Community

Cover image for Building a Simple Rust CLI Tool for File Operations
HexShift
HexShift

Posted on

Building a Simple Rust CLI Tool for File Operations

In this tutorial, we will build a basic Rust command-line tool to perform file operations such as creating, reading, writing, and deleting files. This will give you a solid foundation for using Rust to manage files and implement command-line tools that interact with the filesystem.


Step 1: Set Up Your Project

To start, create a new Rust project:

cargo new file_operations_cli --bin
cd file_operations_cli
Enter fullscreen mode Exit fullscreen mode

This initializes a new project with a main.rs file where we will implement our logic.


Step 2: Add Dependencies

For file operations, we don’t need any external libraries as Rust’s standard library offers robust support for file I/O. However, we’ll use clap for argument parsing to make the tool more flexible. Add clap to Cargo.toml:

[dependencies]
clap = "3.0"
Enter fullscreen mode Exit fullscreen mode

Step 3: Implement File Operations

Next, we will implement the functionality to create, read, write, and delete files using Rust's standard library.

Here's the code for main.rs:

use clap::{App, Arg};
use std::fs::{self, OpenOptions};
use std::io::{self, Write};

fn create_file(file_name: &str) -> io::Result<()> {
    let mut file = OpenOptions::new().create(true).write(true).open(file_name)?;
    writeln!(file, "This is a simple file created with Rust!")?;
    Ok(())
}

fn read_file(file_name: &str) -> io::Result {
    let content = fs::read_to_string(file_name)?;
    Ok(content)
}

fn delete_file(file_name: &str) -> io::Result<()> {
    fs::remove_file(file_name)?;
    Ok(())
}

fn main() {
    let matches = App::new("File Operations CLI")
        .version("1.0")
        .author("Your Name")
        .about("A simple CLI tool for file operations")
        .arg(Arg::new("create")
            .about("Creates a new file")
            .takes_value(true))
        .arg(Arg::new("read")
            .about("Reads a file")
            .takes_value(true))
        .arg(Arg::new("delete")
            .about("Deletes a file")
            .takes_value(true))
        .get_matches();

    if let Some(file_name) = matches.value_of("create") {
        if let Err(e) = create_file(file_name) {
            eprintln!("Error creating file: {}", e);
        } else {
            println!("File '{}' created successfully.", file_name);
        }
    }

    if let Some(file_name) = matches.value_of("read") {
        match read_file(file_name) {
            Ok(content) => println!("{}", content),
            Err(e) => eprintln!("Error reading file: {}", e),
        }
    }

    if let Some(file_name) = matches.value_of("delete") {
        if let Err(e) = delete_file(file_name) {
            eprintln!("Error deleting file: {}", e);
        } else {
            println!("File '{}' deleted successfully.", file_name);
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

This Rust CLI tool provides the following operations:

  • Create a file: cargo run -- create filename.txt
  • Read a file: cargo run -- read filename.txt
  • Delete a file: cargo run -- delete filename.txt

Step 4: Build and Test the Tool

Build and run the tool to perform file operations:

cargo build --release
./target/release/file_operations_cli --create example.txt
./target/release/file_operations_cli --read example.txt
./target/release/file_operations_cli --delete example.txt
Enter fullscreen mode Exit fullscreen mode

You should see the file being created, read, and deleted as specified in the commands.


Use Case Scenario

This tool is perfect for situations where you need a simple way to automate file management tasks. For example, you could use it to generate log files, read configuration files, or clean up temporary files from a server. With minimal setup and no need for complex libraries, you can extend this tool to perform more sophisticated file operations as needed.


✅ Pros and ❌ Cons of Using Rust for CLI Tools

✅ Pros:

  • ⚡ Rust’s performance makes file operations incredibly fast, even with large files.
  • 🛠️ clap makes parsing arguments easy, and you can extend the functionality as needed.
  • 🧩 Rust’s strong type system prevents errors and ensures robustness in file handling.
  • 📂 The tool interacts with the file system directly, making it suitable for automated tasks.

❌ Cons:

  • 📘 Rust’s learning curve can be challenging for beginners compared to scripting languages like Python.
  • 🧩 Advanced file operations like concurrent access or encryption would require more sophisticated libraries and setup.

Summary

In this tutorial, we built a simple Rust command-line tool for performing basic file operations such as creating, reading, and deleting files. We used clap for argument parsing and Rust’s standard library for file I/O operations. This tool is a great starting point for automating file management tasks and can be expanded for more complex use cases.

For more on crafting powerful Rust CLI tools, check out my 15-page guide:

Crafting Command-Line Tools in Rust: A Practical Guide to Building Fast, Reliable Utilities — just $5.


If this was helpful, you can also support me here: Buy Me a Coffee

Top comments (0)