Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

File-argument in libc::stat in Rust

Tags:

rust

libc

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.

like image 846
hansaplast Avatar asked Mar 12 '23 03:03

hansaplast


1 Answers

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.

like image 168
malbarbo Avatar answered Mar 28 '23 21:03

malbarbo