listdir.c 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  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. void list_dir(const char* path)
  18. {
  19. char * fullpath = RT_NULL;
  20. DIR *dir;
  21. dir = opendir(path);
  22. if (dir != RT_NULL)
  23. {
  24. struct dirent* dirent;
  25. struct stat s;
  26. fullpath = rt_malloc(256);
  27. if (fullpath == RT_NULL)
  28. {
  29. closedir(dir);
  30. rt_kprintf("no memory\n");
  31. return;
  32. }
  33. do
  34. {
  35. dirent = readdir(dir);
  36. if (dirent == RT_NULL) break;
  37. rt_memset(&s, 0, sizeof(struct stat));
  38. /* build full path for each file */
  39. rt_sprintf(fullpath, "%s/%s", path, dirent->d_name);
  40. stat(fullpath, &s);
  41. if ( s.st_mode & S_IFDIR )
  42. {
  43. rt_kprintf("%s\t\t<DIR>\n", dirent->d_name);
  44. }
  45. else
  46. {
  47. rt_kprintf("%s\t\t%lu\n", dirent->d_name, s.st_size);
  48. }
  49. } while (dirent != RT_NULL);
  50. closedir(dir);
  51. }
  52. else
  53. {
  54. rt_kprintf("open %s directory failed\n", path);
  55. }
  56. if (RT_NULL != fullpath)
  57. {
  58. rt_free(fullpath);
  59. }
  60. }
  61. #ifdef RT_USING_FINSH
  62. #include <finsh.h>
  63. FINSH_FUNCTION_EXPORT(list_dir, list directory);
  64. static void cmd_list_dir(int argc, char *argv[])
  65. {
  66. char* filename;
  67. if(argc == 2)
  68. {
  69. filename = argv[1];
  70. }
  71. else
  72. {
  73. rt_kprintf("Usage: list_dir [file_path]\n");
  74. return;
  75. }
  76. list_dir(filename);
  77. }
  78. MSH_CMD_EXPORT_ALIAS(cmd_list_dir, list_dir, list directory);
  79. #endif /* RT_USING_FINSH */