1 /*
2 * Copyright (c) 2006-2021, RT-Thread Development Team
3 *
4 * SPDX-License-Identifier: Apache-2.0
5 *
6 * Change Logs:
7 * Date Author Notes
8 * 2010-02-10 Bernard first version
9 * 2020-04-12 Jianjia Ma add msh cmd
10 */
11 #include <rtthread.h>
12 #include <dfs_file.h>
13 #include <unistd.h>
14 #include <stdio.h>
15 #include <sys/stat.h>
16 #include <sys/statfs.h>
17
list_dir(const char * path)18 void list_dir(const char* path)
19 {
20 char * fullpath = RT_NULL;
21 DIR *dir;
22
23 dir = opendir(path);
24 if (dir != RT_NULL)
25 {
26 struct dirent* dirent;
27 struct stat s;
28
29 fullpath = rt_malloc(256);
30 if (fullpath == RT_NULL)
31 {
32 closedir(dir);
33 rt_kprintf("no memory\n");
34 return;
35 }
36
37 do
38 {
39 dirent = readdir(dir);
40 if (dirent == RT_NULL) break;
41 rt_memset(&s, 0, sizeof(struct stat));
42
43 /* build full path for each file */
44 rt_sprintf(fullpath, "%s/%s", path, dirent->d_name);
45
46 stat(fullpath, &s);
47 if ( s.st_mode & S_IFDIR )
48 {
49 rt_kprintf("%s\t\t<DIR>\n", dirent->d_name);
50 }
51 else
52 {
53 rt_kprintf("%s\t\t%lu\n", dirent->d_name, s.st_size);
54 }
55 } while (dirent != RT_NULL);
56
57 closedir(dir);
58 }
59 else
60 {
61 rt_kprintf("open %s directory failed\n", path);
62 }
63
64 if (RT_NULL != fullpath)
65 {
66 rt_free(fullpath);
67 }
68 }
69
70 #ifdef RT_USING_FINSH
71 #include <finsh.h>
72 FINSH_FUNCTION_EXPORT(list_dir, list directory);
73
cmd_list_dir(int argc,char * argv[])74 static void cmd_list_dir(int argc, char *argv[])
75 {
76 char* filename;
77
78 if(argc == 2)
79 {
80 filename = argv[1];
81 }
82 else
83 {
84 rt_kprintf("Usage: list_dir [file_path]\n");
85 return;
86 }
87 list_dir(filename);
88 }
89 MSH_CMD_EXPORT_ALIAS(cmd_list_dir, list_dir, list directory);
90 #endif /* RT_USING_FINSH */
91