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编译不过,重新手写就过,反复确认了几次,粘贴的与手写的模一样的(包手大小写),不知是什么原因?
参考:https://www.it610.com/article/1295494501065891840.htm
https://www.e-learn.cn/topic/3714081
https://blog.csdn.net/wowotuo/article/details/86827869