rust windows-rs 调用GetLogicalDriveStringsW显示硬盘目录

win10系统 

Cargo.toml

[dependencies]
windows = "0.19"
encoding = "0.2"

[build-dependencies]
windows = "0.19"

main.rs

mod bindings {
    windows::include_bindings!();
}

use {bindings::Windows::Win32,
 Win32::Foundation::PWSTR,
 Win32::Storage::FileSystem::GetLogicalDriveStringsW,
};
use std::process::Command;
use encoding::all::GB18030;
use encoding::{DecoderTrap,Encoding};

fn main()  {     
   unsafe{
    let mut text: [u16; 512] = [0; 512];
    let len = GetLogicalDriveStringsW(text.len() as u32,PWSTR(text.as_mut_ptr()));   
    let text = String::from_utf16_lossy(&text[..len as usize]);
    if !text.is_empty() {
        println!("本地所有磁盘:{}", text);
    }
    let pos:Vec<&str> = text.split("\u{0}").filter(|v|!v.is_empty()).collect();   
    //println!("pos:{:?}", pos);
    let hdd2=   pos.get(2).unwrap();
    println!("第2个盘符:{}", hdd2);
    let cmd_str1 = String::from("dir ");
    let cmd_str2 = hdd2.to_string();
    let cmd_str =format!("{}{}",cmd_str1,cmd_str2);
    //let cmd_str6:&str  = &cmd_str;
    //let cmd_str5 ="dir E:";
    //assert_eq!(cmd_str6,cmd_str5);
    println!("cmd命令:{}", cmd_str);
    let output =Command::new("cmd").arg("/c").arg(cmd_str.to_string()).output()
    .ok().expect("cmd exec error!").stdout;   
    let output_str2:&[u8]= &output;
    let output_str3=GB18030.decode(output_str2, DecoderTrap::Strict).unwrap();
    println!("{}", output_str3);
}
}

build.rs

fn main() {
    windows::build! {       
        Windows::Win32::Storage::FileSystem::GetLogicalDriveStringsW,    
    };
}
原文地址:https://www.cnblogs.com/pu369/p/15246242.html