listdir.c 1.6 KB

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