Rust调用Windows dir命令报错:程序未找到
问题原因
dir是Windows系统中cmd.exe的内置命令,并非独立的可执行程序。std::process::Command::new()只能调用可执行文件,因此直接传入"dir"会提示“程序未找到”。
解决方案
方法1:通过cmd.exe执行dir命令
调用cmd.exe并传递/c dir参数,让cmd来执行内置的dir命令:
use std::process::Command; fn main() { let res = Command::new("cmd") .args(["/c", "dir"]) .output(); println!("{:?}", res); }
/c参数表示执行完指定命令后关闭cmd进程
方法2:使用Rust标准库直接读取目录(推荐)
用std::fs::read_dir直接操作文件系统,这是更符合Rust风格的实现,无需依赖外部命令:
use std::fs; fn main() { match fs::read_dir(".") { Ok(entries) => { for entry in entries { if let Ok(entry) = entry { println!("{}", entry.file_name().to_string_lossy()); } } } Err(e) => println!("读取目录失败: {}", e), } }
内容的提问来源于stack exchange,提问作者Kavin Bharathi
相关产品推荐
相关产品推荐

