use std::fs::{OpenOptions, File};
use std::io::{self, Write, BufRead, BufReader};
use std::time::{SystemTime, UNIX_EPOCH};
fn main() {
loop {
println!("\n--- Notes Menu ---");
println!("1) Add a note");
println!("2) Show all notes");
println!("3) Edit a note");
println!("4) Exit");
print!("Choose an option: ");
io::stdout().flush().unwrap();
let mut choice = String::new();
io::stdin().read_line(&mut choice).unwrap();
match choice.trim() {
"1" => add_note(),
"2" => show_notes(),
"3" => edit_note(),
"4" => {
println!("Goodbye!");
break;
}
_ => println!("Invalid option."),
}
}
}
fn add_note() {
print!("Enter your note: ");
io::stdout().flush().unwrap();
let mut note = String::new();
io::stdin().read_line(&mut note).unwrap();
let note = note.trim();
if note.is_empty() {
println!("Note cannot be empty.");
return;
}
let timestamp = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_secs();
let mut file = OpenOptions::new()
.create(true)
.append(true)
.open("notes.txt")
.unwrap();
writeln!(file, "[{}] {}", timestamp, note).unwrap();
println!("Note added.");
}
fn show_notes() {
let notes = load_notes();
if notes.is_empty() {
println!("No notes yet.");
return;
}
println!("\n--- All Notes ---");
for (i, note) in notes.iter().enumerate() {
println!("{}: {}", i + 1, note);
}
}
fn edit_note() {
let mut notes = load_notes();
if notes.is_empty() {
println!("No notes to edit.");
return;
}
show_notes();
print!("Enter the number of the note to edit: ");
io::stdout().flush().unwrap();
let mut input = String::new();
io::stdin().read_line(&mut input).unwrap();
let index: usize = match input.trim().parse::<usize>() {
Ok(n) if n > 0 && n <= notes.len() => n - 1,
_ => {
println!("Invalid note number.");
return;
}
};
println!("\nCurrent note:\n{}", notes[index]);
print!("Enter new text: ");
io::stdout().flush().unwrap();
let mut new_text = String::new();
io::stdin().read_line(&mut new_text).unwrap();
let new_text = new_text.trim();
if new_text.is_empty() {
println!("Note cannot be empty.");
return;
}
// Update note text, keep timestamp
if let Some(end_bracket) = notes[index].find("]") {
notes[index] = format!("{} {}", ¬es[index][..=end_bracket], new_text);
}
save_notes(¬es);
println!("Note updated!");
show_notes();
println!("\nPress Enter to continue...");
let mut pause = String::new();
io::stdin().read_line(&mut pause).unwrap();
}
fn load_notes() -> Vec<String> {
let file = match File::open("notes.txt") {
Ok(f) => f,
Err(_) => return vec![],
};
let reader = BufReader::new(file);
reader.lines().map(|l| l.unwrap()).collect()
}
fn save_notes(notes: &[String]) {
let mut file = File::create("notes.txt").unwrap();
for n in notes {
writeln!(file, "{}", n).unwrap();
}
}