file-io - 打开文件返回ErrorKind::Other 'Error: Os, code: 20, message: “Not a directory”'

标签 file-io rust

我正在尝试打开一个文件,如果不存在,请创建它。但是由于某种原因,我收到一条消息ErrorKind::Other"Not a directory"错误。这是我得到的完整错误:

thread 'main' panicked at 'Unknown error when opening file: Os { code: 20, kind: Other, message: "Not a directory" }', src/main.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",这是正确的。

有谁知道为什么我会收到操作系统错误20“不是目录”?

PS我在Windows 10内部版本18909上运行的WSL中​​使用Rust nightly-x86_64-unknown-linux-gnu和rustc版本1.46.0-nightly

最佳答案

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

关于file-io - 打开文件返回ErrorKind::Other 'Error: Os, code: 20, message: “Not a directory”',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62303615/

相关文章:

c++ - 在二进制文件中保存和加载游戏状态。 C++

rust - rust 错误: value of type `std::vec::Vec<i32>` cannot be built from `std::iter::Iterator<Item=&i32>`

error-handling - 宏匹配臂模式 “no rules expected the token ` if`”

java - 在java中单行编辑文件

java - 如何删除目录中上传的相同文件?

static - 如何在没有赋值的情况下声明静态可变变量?

c - 链接ARM C和Rust

struct - 如何重载 'new' 方法?

Android:将文件保存到内部数据时需要 BufferedOutputStream 吗?

java - Java 中的扫描器