listdir.c 1.8 KB

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