I'm struggling to call libc::stat
in Rust. I have this:
extern crate libc;
use std::fs::File;
use std::os::unix::prelude::*;
use std::path::Path;
fn main() {
let p = Path::new("/");
let f = File::open(&p).unwrap();
let fd = f.as_raw_fd() as i8;
unsafe {
let mut stat: libc::stat = std::mem::zeroed();
if libc::stat(fd, &mut stat) >= 0 {
println!("{}", stat.st_blksize);
}
}
}
but now I receive this error: error: mismatched types: expected *const i8, found i8
I couldn't find any documentation on how the first argument works. Judging from the type (i8
) I thought it must be file descriptor.
Background: I'm reading through "Advanced Programming in the UNIX Environment" and want to do some exercises in Rust instead of C.
The first argument to stat
is the file path as a C string. C strings are represented in Rust by CStr
(borrowed) or CString
(owned). Here is an example using CString
:
extern crate libc;
use std::ffi::CString;
fn main() {
unsafe {
let root = CString::new("/").unwrap();
let mut stat: libc::stat = std::mem::zeroed();
if libc::stat(root.as_ptr(), &mut stat) >= 0 {
println!("{}", stat.st_blksize);
}
}
}
Take a look at the FFI chapter of the Rust Book for other information.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With