gpt4 book ai didi

error-handling - 有没有办法从std::io::Error获取OS错误代码?

转载 作者:行者123 更新时间:2023-12-03 11:32:07 25 4
gpt4 key购买 nike

当我运行以下命令时:

use std::fs::File;

fn main() {
let filename = "not_exists.txt";
let reader = File::open(filename);

match reader {
Ok(_) => println!(" * file '{}' opened successfully.", filename),
Err(e) => {
println!("{:?}", &e);
}
}
}
输出为:
Os { code: 2, kind: NotFound, message: "No such file or directory" }
是否可以将该代码作为整数获取?

最佳答案

使用 io::Error::raw_os_error :

match reader {
Ok(_) => println!(" * file '{}' opened successfully.", filename),
Err(e) => println!("{:?}", e.raw_os_error()),
}
输出:
Some(2)
也可以看看:
  • How does one get the error message as provided by the system without the "os error n" suffix?
  • 关于error-handling - 有没有办法从std::io::Error获取OS错误代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66212606/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com