pu369com

rust:win10执行shell命令及GB18030decode解码utf8存盘

费了点劲的知识点:

1 crate encoding处理汉字

2  Vec<u8>转&[u8]

代码(win10系统):

extern crate encoding;
use std::process::Command;
use encoding::all::GB18030;
use encoding::{DecoderTrap,EncoderTrap,Encoding};
use std::io::{self, Write};
use std::fs::File;
fn main(){
let cmd_str: String;
// cmd_str例子:"dir c:\\ (这里必须有一个空格才行) "   而且,如果这里不用\\而是用/的话,会被windows认为/tmp的/t是一个option而报错
cmd_str = "echo 我A1".to_string();
let result1 =   Command::new("cmd").arg("/c").arg(cmd_str).output()
.ok().expect("cmd exec error!").stdout;
println!("result1: {:?}", result1);  //result1: [206, 210, 65, 49, 13, 10]
let result2 = String::from_utf8_lossy(&result1);
println!("result2: {:?}", result2);  //result2: "��A1\r\n"
let result3:&[u8] = &result1;
let result4=GB18030.decode(result3, DecoderTrap::Strict).unwrap();
println!("result4: {:?}", result4);   //result4: "我A1\r\n"
savef(result4);  //在Cargo.toml所在目录生成了data.txt
}
fn savef(txt:String){
    let mut file1 = std::fs::File::create("data.txt").expect("create failed");
    file1.write_all(txt.as_bytes()).expect("write failed");    
}

在VScode中写代码时, 粘贴过来的write_all编译不过,重新手写就过,最后发现是手写时,VScode自动给添加了use std::io::{self, Write};果然是强大的VScode

补充:在 toml文件[dependencies]下加入:encoding = "0.2"

 

参考:https://www.it610.com/article/1295494501065891840.htm

https://www.e-learn.cn/topic/3714081

https://blog.csdn.net/wowotuo/article/details/86827869

posted on 2021-08-21 17:53  pu369com  阅读(468)  评论(0编辑  收藏  举报

导航