rust todo cli app example

Sure, here is an example of how you can create a simple todo CLI app in Rust:

rust todo cli app example

use std::env;
use std::fs;
use std::io::{self, Write};
use std::process;

fn main() {
    let args: Vec<String> = env::args().collect();

    if args.len() < 2 {
        println!("Usage: todo <command> [<args>]");
        process::exit(1);
    }

    let command = &args[1];
    let task = &args[2];

    match command.as_ref() {
        "add" => add_task(task),
        "list" => list_tasks(),
        "done" => mark_done(task),
        _ => println!("Invalid command"),
    }
}

fn add_task(task: &str) {
    let mut file = fs::OpenOptions::new()
        .append(true)
        .open("tasks.txt")
        .unwrap();

    if let Err(e) = writeln!(file, "{}", task) {
        eprintln!("Couldn't write to file: {}", e);
    }
}

fn list_tasks() {
    let contents = fs::read_to_string("tasks.txt").unwrap();

    for (i, line) in contents.lines().enumerate() {
        println!("{}. {}", i + 1, line);
    }
}

fn mark_done(task_num: &str) {
    let mut contents = fs::read_to_string("tasks.txt").unwrap();
    let mut lines: Vec<&str> = contents.split("\n").collect();
    let task_num: usize = task_num.parse().unwrap();

    if task_num > 0 && task_num <= lines.len() {
        lines[task_num - 1] = "DONE";

        let new_contents = lines.join("\n");
        fs::write("tasks.txt", new_contents).unwrap();
    } else {
        println!("Invalid task number");
    }
}

This app has three commands: add, list, and done.

To add a task, you can run todo add <task>. This will append the task to the tasks.txt file.

To list all tasks, you can run todo list. This will read the tasks.txt file and print all the tasks.

To mark a task as done, you can run todo done <task_num>. This will replace the task at the specified task number with the string “DONE”.

I hope this helps! Let me know if you have any questions.

 

Leave a Reply

Your email address will not be published. Required fields are marked *