2013-12-08 40 views
1

我是Rust新手,我試圖編寫hostname實用程序來構建core-utils的生鏽backport。這裏更多:https://github.com/uutils/coreutilsRust,如何與gethostname()相互作用std :: libc

我有以下程序:

use std::libc; 

extern { 
    pub fn gethostname(name: *libc::c_char, size: libc::size_t) -> libc::c_int; 
} 


fn main() { 
    unsafe { 
    let len = 34 as uint; 
    let mut buf = std::vec::with_capacity(len); 
    std::vec::raw::set_len (&mut buf, len as uint); 

    gethostname (std::vec::raw::to_ptr(buf), len as u64); 
    println(format!("{:?}", buf)); 

    println(format!("{:?}", len)); 
    //println(std::str::from_chars(buf)); 
    } 
} 

我試圖打印到任何的gethostname份焦炭中的載體,但我得到的東西看起來並不像一個字符串。

~[65i8, 108i8, 97i8, 110i8, 115i8, 45i8, 77i8, 97i8, 99i8, 66i8, 111i8, 111i8, 107i8, 45i8, 80i8, 114i8, 111i8, 46i8, 108i8, 111i8, 99i8, 97i8, 108i8, 0i8, 0i8, 0i8, 0i8, 0i8, 0i8, 0i8, 0i8, 0i8, 0i8, 0i8] 
34u 

我需要爲了做到: 1.確保的gethostname()是做什麼的,我認爲是幹什麼的? 2.確保我編碼正確嗎?

回答

1

buf~[u8]並且是這樣打印的(即任意數字的向量); std::str::from_utf8_ownedstd::str::from_utf8_slice將(推測)UTF-8 [u8]轉換爲str。 (後者在主叫from_utf8; 0.8 from_utf8是壞的,併除去,但它的分配和拷貝,而這兩個既不做。)

因此,像

use std::{libc, str, vec}; 

extern { 
    pub fn gethostname(name: *mut libc::c_char, size: libc::size_t) -> libc::c_int; 
} 


fn main() { 
    let len = 34u; 
    let mut buf = std::vec::from_elem(len, 0u8); 

    let err = unsafe {gethostname (vec::raw::to_mut_ptr(buf) as *mut i8, len as u64)}; 
    if err != 0 { println("oops, gethostname failed"); return; } 

    // find the first 0 byte (i.e. just after the data that gethostname wrote) 
    let actual_len = buf.iter().position(|byte| *byte == 0).unwrap_or(len); 

    // trim the hostname to the actual data written 
    println(str::from_utf8_slice(buf.slice_to(actual_len))); 
} 

將打印主機名。

文檔: