filerustpath

Is it possible to get the path from an opened file object in Rust?


Let's suppose I have an instance of std::fs::File opened. Is there a way to access the full path to this file via inner methods?

std::fs::Metadata does not seem to have this information. I am asking this question because I need this path and perhaps I can avoid keeping it in a separate variable.


Solution

  • Unfortunately, it is not possible. A File only describes an operating system file handle/file descriptor, depending on the specific operating system. For instance, the implementation of File on Unix'y systems has only a file descriptor in the File object:

    pub struct File(FileDesc);

    More digging through structs eventually leads to a RawFd which is just c_int.

    Checking the size of the struct confirms this:

        println!("{}", std::mem::size_of::<std::fs::File>())
        // prints 4 on Unix'y systems
    

    Furthermore, these may not be unambiguously associated with a filename. They could, for instance, be associated with a raw FD obtained from somewhere, an inode that doesn't have a file name associated with it anymore, an inode with multiple distinct hardlinks and hence multiple names. There are some tricks in this question as kmdreko points out, but they seem overly brittle and non-portable just to avoid keeping the name in a variable.