Rust中的libc :: stat中的文件参数

han*_*ast 3 libc rust

我很难打电话给libc::statRust.我有这个:

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);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

但现在我收到这个错误: error: mismatched types: expected *const i8, found i8

我找不到关于第一个参数如何工作的任何文档.从类型(i8)来看,我认为它必须是文件描述符.

背景:我正在阅读"UNIX环境中的高级编程",并希望在Rust中进行一些练习而不是C.

mal*_*rbo 5

第一个参数stat是文件路径为C字符串.C字符串用Rust表示CStr(借用)或CString(拥有).这是一个使用示例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);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

有关其他信息,请查看Rust Book 的FFI章节.