Fedorov7890
Fedorov7890

Reputation: 1255

Is there a way to get an OS error code from a std::io::Error?

When I run the following:

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);
        }
    }
}

The output is:

Os { code: 2, kind: NotFound, message: "No such file or directory" }

Is it possible to get that code as an integer?

Upvotes: 2

Views: 1309

Answers (2)

pretzelhammer
pretzelhammer

Reputation: 15165

Yes, use the raw_os_error method on std::io::Error. Example:

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, e.raw_os_error());
        }
    }
}

playground

Upvotes: 3

Shepmaster
Shepmaster

Reputation: 432199

Use io::Error::raw_os_error:

match reader {
    Ok(_) => println!(" * file '{}' opened successfully.", filename),
    Err(e) => println!("{:?}", e.raw_os_error()),
}

Output:

Some(2)

See also:

Upvotes: 5

Related Questions