打开文件返回ErrorKind::Other 'Error: Os, code: 20, message: "不是一个目录"'

问题描述 投票:0回答:1

我试图打开一个文件,如果它不存在,就创建它。但由于某些原因,我收到了一个错误信息,即 ErrorKind::Other 附带信息 "Not a directory". 以下是我得到的完整错误信息。

线程'main'在'打开文件时出现未知错误'时惊慌失措。Os { code: 20, kind: 其他,信息:"Not a directory" }', srcmain.rs:53:00 "Not a directory" }', srcmain.rs:53:17。

这是我的代码。

let mut filepath = std::env::current_exe()?;
filepath.push("days");
filepath.set_extension("toml");

let mut file = match File::open(filepath.clone()) {
    Ok(f) => f,
    Err(e) => match e.kind() {
        ErrorKind::NotFound => {
            {
                let mut create_file = File::create(filepath.clone());
                create_file.write_all(...); // Dummy data
            }
            File::open(filepath.clone())?
        },
        _ => {
            panic!("Unknow error when opening file: {:?}", e); // This is line 53
        }
    }
};         

当我把文件路径打印到控制台检查时,我得到的是 "/mnt/c/Projects/Other/random/hmdict/target/debug/hmdict/days.toml",这是正确的。

有谁知道为什么我收到os错误20 "不是一个目录"?

P.S 我使用的是Rust nightly-x86_64-unknown-linux-gnu 与Rustc版本 1.46.0-nightly 在WSL中运行在Windows 10构建18363版本1909上

file-io rust
1个回答
3
投票

问题是 推动 创建一个单独的路径。如果您的可执行文件位置是 <what_ever>/hmdict,你的代码创建了一个路径 <whatever>/hmdict/days.toml. 显然,这条路径并不存在,因为 hmdict 是一个可执行文件,而不是一个目录。

© www.soinside.com 2019 - 2024. All rights reserved.