br_file/
lib.rs

1use std::{fs};
2use std::fs::{DirBuilder};
3use std::path::{Path};
4
5
6/// 创建目录
7///
8/// * path 路径带文件名 /home/roger/foo/bar/baz.txt
9pub fn create_dir(mut path: &str) -> Result<(), String> {
10    if path.contains(".") {
11        let data = Path::new(path);
12        let data = data.parent().unwrap();
13        path = data.to_str().unwrap();
14    }
15    return match DirBuilder::new().recursive(true).create(path) {
16        Ok(_) => {
17            Ok(())
18        }
19        Err(e) => {
20            Err(e.to_string())
21        }
22    };
23}
24
25/// 获取目录下所有文件列表
26pub fn get_file_list(path: &str) -> Result<Vec<String>, String> {
27    let mut files = vec![];
28    let paths = match fs::read_dir(path) {
29        Ok(e) => e,
30        Err(e) => {
31            return Err(e.to_string());
32        }
33    };
34    for path in paths {
35        match path {
36            Ok(e) => {
37                if e.path().is_file() {
38                    let e = e.path().clone();
39                    let file_name = e.as_os_str().to_str().unwrap().clone();
40                    files.push(file_name.to_string());
41                } else {
42                    if e.path().is_dir() {
43                        let e = e.path().clone();
44                        let dir_name = e.as_os_str().to_str().unwrap().clone();
45                        match get_file_list(dir_name) {
46                            Ok(e) => {
47                                files.extend(e);
48                            }
49                            Err(e) => {
50                                return Err(e.to_string());
51                            }
52                        };
53                    }
54                }
55            }
56            Err(e) => {
57                return Err(e.to_string());
58            }
59        }
60    }
61    Ok(files)
62}
63
64/// 获取目录下文件夹列表
65pub fn get_dir_list(path: &str) -> Result<Vec<String>, String> {
66    let mut dirs = vec![];
67    let paths = fs::read_dir(path).unwrap();
68    for path in paths {
69        match path {
70            Ok(e) => {
71                if e.path().is_dir() {
72                    dirs.push(e.file_name().to_str().unwrap().to_string().clone());
73                }
74            }
75            Err(e) => {
76                return Err(e.to_string());
77            }
78        }
79    }
80    return Ok(dirs);
81}