【Rust】用libc实现文件拷贝

#[macro_export]
macro_rules! c_string {
    ($s:expr)=> (
        {
            use std::ffi::{CString};
            CString::new($s).unwrap().as_ptr()
        }
    )
}

#[macro_export]
macro_rules! check_pointer {
    (let $p:ident $(: $t:ty)? =  $($f:ident)::*  ( $($a:expr),* )   ) => {
        let $p $(: $t)? = $($f)::* (  $($a),*  ) ;
        if $p.is_null() {
            libc::perror(c_string!(stringify!($($f)::*)));
            libc::exit(1);
        }
    };
}



use libc::{fputc, putchar};
#[test]
fn test_file_copy() {

    unsafe {
        let mut ch;
        
		check_pointer! {
        	let fp = libc::fopen(c_string!("/home/sun/src/hexfile.cc") ,c_string!("r"));
        }
      
       	check_pointer! {
        	let out = libc::fopen(c_string!("/home/sun/src/out_hexfile.txt") , c_string!("w") );
       	}
       	
        loop{
            ch = libc::fgetc(fp);
            if ch == libc::EOF { break; }
            fputc(ch,out);
        }

        libc::fclose(fp);
        libc::fclose(out);

    }
}

你可能感兴趣的:(rust,开发语言,后端)