listdir.c 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  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_posix.h>
  13. void list_dir(const char* path)
  14. {
  15. char * fullpath = RT_NULL;
  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. if (RT_NULL != fullpath)
  53. {
  54. rt_free(fullpath);
  55. }
  56. }
  57. #ifdef RT_USING_FINSH
  58. #include <finsh.h>
  59. FINSH_FUNCTION_EXPORT(list_dir, list directory);
  60. static void cmd_list_dir(int argc, char *argv[])
  61. {
  62. char* filename;
  63. if(argc == 2)
  64. {
  65. filename = argv[1];
  66. }
  67. else
  68. {
  69. rt_kprintf("Usage: list_dir [file_path]\n");
  70. return;
  71. }
  72. list_dir(filename);
  73. }
  74. MSH_CMD_EXPORT_ALIAS(cmd_list_dir, list_dir, list directory);
  75. #endif /* RT_USING_FINSH */