Reputation: 6912
I am writing binding for a C library, I'd like to call std::io::File::open
as it's got error handling already. I then intend to pass the fd
to C function.
I have looked at std::io::fs, but the fd
field is nothing like what I would have thought.
After some more digging I found native::io::file::FileDesc, which indeed has fn fd(&self) -> fd_t
, but doesn't seem like this is something I can access from an instance of std::io::File
.
There appear to be fs_from_raw_fd method, it's the exact opposite to what I need.
Upvotes: 1
Views: 3324
Reputation: 61
use std::os::unix::io::AsRawFd;
let path = Path::new("my.txt");
let display = path.display();
let mut file = match File::open(&path) {
// The `description` method of `io::Error` returns a string that
// describes the error
Err(why) => panic!("couldn't open {}: {}", display,
why.description()),
Ok(file) => file,
};
println!("file descriptor: {}",file.as_raw_fd());
Upvotes: 6
Reputation: 898
The closest you can get in the current version of Rust is via native::io::file::open
.
use native::io::file::open;
use std::rt::rtio::{Open, Read};
let file = match open(&path.to_c_str(), Open, Read) {
Ok(file) => file,
Err(_) => return,
}
let fd = file.fd();
Upvotes: 2