You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.23 05:54:38