listdir.c 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  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. }
  50. while (dirent != RT_NULL);
  51. closedir(dir);
  52. }
  53. else
  54. {
  55. rt_kprintf("open %s directory failed\n", path);
  56. }
  57. if (RT_NULL != fullpath)
  58. {
  59. rt_free(fullpath);
  60. }
  61. }
  62. #ifdef RT_USING_FINSH
  63. #include <finsh.h>
  64. FINSH_FUNCTION_EXPORT(list_dir, list directory);
  65. static void cmd_list_dir(int argc, char *argv[])
  66. {
  67. char *filename;
  68. if (argc == 2)
  69. {
  70. filename = argv[1];
  71. }
  72. else
  73. {
  74. rt_kprintf("Usage: list_dir [file_path]\n");
  75. return;
  76. }
  77. list_dir(filename);
  78. }
  79. MSH_CMD_EXPORT_ALIAS(cmd_list_dir, list_dir, list directory);
  80. #endif /* RT_USING_FINSH */