一,输出道得经到D盘
use std::fs::File;
use std::io::{ Error, Write};
fn main() -> Result<(), Error> {
let path = "D:/道德经.txt";
let vec = vec![
"第一章",
"道可道也,非恒道也。",
"名可名也,非恒名也。",
"无名,万物之始也;有名,万物之母也。",
"故恒无欲也,以观其眇;恒有欲也,以观其所徼。",
"两者同出,异名同谓。",
"玄之又玄,众眇之门。",
];
let mut output = File::create(path)?;
writeln!(output, "{:?}", vec)?;
read(&path);
Ok(())
}
效果如下:
显然有数组的 [] 中括号,况且没有格式,进行制表符的拼接,对代码做以下调整:
use std::fs::File;
use std::io::{BufRead, BufReader, Error, Write};
fn main() -> Result<(), Error> {
let path = "D:/道德经.txt";
let vec = vec![
"第一章",
"道可道也,非恒道也。",
"名可名也,非恒名也。",
"无名,万物之始也;有名,万物之母也。",
"故恒无欲也,以观其眇;恒有欲也,以观其所徼。",
"两者同出,异名同谓。",
"玄之又玄,众眇之门。",
];
let mut my_str = String::new();
for v in vec.iter() {
my_str.push_str(v);
my_str.push_str("\n");
}
let mut output = File::create(path)?;
writeln!(output, "{}", my_str)?;
Ok(())
}
效果如下:
二,把输出道得经 从D盘的文件中读取出来
use std::fs::File;
use std::io::{BufRead, BufReader, Error, Write};
fn main() -> Result<(), Error> {
let path = "D:/道德经.txt";
let vec = vec![
"第一章",
"道可道也,非恒道也。",
"名可名也,非恒名也。",
"无名,万物之始也;有名,万物之母也。",
"故恒无欲也,以观其眇;恒有欲也,以观其所徼。",
"两者同出,异名同谓。",
"玄之又玄,众眇之门。",
];
let mut my_str = String::new();
for v in vec.iter() {
my_str.push_str(v);
my_str.push_str("\n");
}
let mut output = File::create(path)?;
writeln!(output, "{}", my_str)?;
read(&path);
Ok(())
}
fn read(path: &str) -> Result<(), Error> {
let input = File::open(path)?;
let buffered = BufReader::new(input);
for line in buffered.lines() {
println!("{}", line?);
}
Ok(())
}
效果如下:
扫描二维码关注公众号,回复:
12907968 查看本文章
![](/qrcode.jpg)
三,追加个作者
use std::fs::File;
use std::io::{BufRead, BufReader, Error, Write};
use std::fs::OpenOptions;
fn append(path: &str, app_str: &str) -> Result<(), Error> {
let mut file = OpenOptions::new().append(true).open(path)?;
file.write(b"\n");
file.write_fmt(format_args!("{}", app_str))?;
Ok(())
}
fn main() -> Result<(), Error> {
let path = "D:/道德经.txt";
let app_str = "作者--解决问题no解决代码问题";
append(path, app_str);
Ok(())
}
效果如下: