listdir.c 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  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. static void cmd_list_dir(int argc, char *argv[])
  64. {
  65. char* filename;
  66. if(argc == 2)
  67. {
  68. filename = argv[1];
  69. }
  70. else
  71. {
  72. rt_kprintf("Usage: list_dir [file_path]\n");
  73. return;
  74. }
  75. list_dir(filename);
  76. }
  77. MSH_CMD_EXPORT_ALIAS(cmd_list_dir, list_dir, list directory);
  78. #endif /* RT_USING_FINSH */