Rust终端音乐播放器开发:无法列出指定目录的文件和文件夹
修复Rust目录文件列表问题
核心问题分析
- 输入路径包含多余换行符:
read_line会将用户输入时的换行符(\n或Windows下的\r\n)一并存入字符串,导致路径无效,read_dir无法识别。 - 错误处理缺失:直接使用
unwrap会在路径不存在、无权限等场景下触发程序panic,且未正确解析目录项的实际路径信息。
修复后的代码
main.rs
use std::path::*; use std::io::*; fn main() { let mut file_path = String::new(); println!("Enter music file path"); stdin().read_line(&mut file_path).expect("Failed to read input"); let trimmed_path = file_path.trim(); rusty_music::display_all_files(Path::new(trimmed_path)); }
lib.rs
use rodio::{source::Source, Decoder, OutputStream}; use std::fs::read_dir; use std::io::BufReader; use std::path::Path; pub fn display_all_files(path: &Path) { println!("Listing contents of: {}", path.display()); match read_dir(path) { Ok(entries) => { for entry in entries { match entry { Ok(dir_entry) => { let entry_path = dir_entry.path(); let entry_type = if entry_path.is_dir() { "Directory" } else if entry_path.is_file() { "File" } else { "Other" }; println!("[{}] {}", entry_type, entry_path.display()); } Err(e) => eprintln!("Failed to read entry: {}", e), } } } Err(e) => eprintln!("Failed to read directory: {}", e), } }
修复关键点
- 去除输入路径的空白字符:通过
trim()清理换行符和前后空格,确保路径有效。 - 替换
unwrap为match错误处理:避免程序崩溃,同时输出明确的错误提示。 - 区分文件与目录:通过
is_dir()和is_file()判断条目类型,让输出更直观。
内容的提问来源于stack exchange,提问作者ayush mishra
相关产品推荐
相关产品推荐

