Get file from std::io::Error

Hello,

I'm getting an std::io::Error which displays as:

File exists (os error 17)

Is there a way to find out from the error which file it is about? Thanks!

Best, Oliver

I don’t think there is a way to find out more information from the error. Searching the standard library for "os error" finds

impl fmt::Display for Error {
    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self.repr {
            Repr::Os(code) => {
                let detail = sys::os::error_string(code);
                write!(fmt, "{} (os error {})", detail, code)
            }
            Repr::Custom(ref c) => c.error.fmt(fmt),
            Repr::Simple(kind) => write!(fmt, "{}", kind.as_str()),
            Repr::SimpleMessage(_, &msg) => msg.fmt(fmt),
        }
    }
}

so that’s the code where your displayed message comes from; the types involved look like

pub struct Error {
    repr: Repr,
}
enum Repr {
    Os(i32),
    Simple(ErrorKind),
    // &str is a fat pointer, but &&str is a thin pointer.
    SimpleMessage(ErrorKind, &'static &'static str),
    Custom(Box<Custom>),
}

internally, so it looks like that io::Error struct you’re having literally only contains the number 17, nothing more.

It's not possible. io::Error does not keep this information. You will have to use your own error type and add paths in places where you know which path is failing.

See also:

https://lib.rs/crates/fs-err

4 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.