Rust基础(12)-文件读写

操作文件

文件的读取、目录的递归

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
use std::fs;
use std::io;
use std::path::Path;

fn visit_dirs(dir:&Path)->io::Result<()>{
if dir.is_dir(){
for entry in fs::read_dir(dir)?{
let entry = entry?;
let path = entry.path();
if path.is_dir(){
visit_dirs(&path);
}else{
let c = fs::read_to_string(path).unwrap();
println!("file = {}",c);
}
}
}
Ok(())
}

fn main() {
let context = fs::read("./test/tt1").unwrap();
println!("content = {:#?}", context);

let context = fs::read_to_string("./test/tt1").unwrap();
println!("content = {:#?}", context);

visit_dirs(Path::new("./test")).unwrap();
}

总结

本文编辑完毕

  • Copyrights © 2017-2023 Jason
  • Visitors: | Views:

谢谢打赏~

微信