Update listdir.c

1.close dir before return;
2.fixed indentation.
This commit is contained in:
David Lin 2020-10-17 11:53:11 +08:00 committed by GitHub
parent 3ff0c07b38
commit adc5dab5b2
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 37 additions and 36 deletions

View File

@ -14,49 +14,50 @@
void list_dir(const char* path) void list_dir(const char* path)
{ {
char * fullpath; char * fullpath;
DIR *dir; DIR *dir;
dir = opendir(path); dir = opendir(path);
if (dir != RT_NULL) if (dir != RT_NULL)
{ {
struct dirent* dirent; struct dirent* dirent;
struct stat s; struct stat s;
fullpath = rt_malloc(256); fullpath = rt_malloc(256);
if (fullpath == RT_NULL) if (fullpath == RT_NULL)
{ {
rt_kprintf("no memory\n"); closedir(dir);
return; rt_kprintf("no memory\n");
} return;
}
do do
{ {
dirent = readdir(dir); dirent = readdir(dir);
if (dirent == RT_NULL) break; if (dirent == RT_NULL) break;
rt_memset(&s, 0, sizeof(struct stat)); rt_memset(&s, 0, sizeof(struct stat));
/* build full path for each file */ /* build full path for each file */
rt_sprintf(fullpath, "%s/%s", path, dirent->d_name); rt_sprintf(fullpath, "%s/%s", path, dirent->d_name);
stat(fullpath, &s); stat(fullpath, &s);
if ( s.st_mode & S_IFDIR ) if ( s.st_mode & S_IFDIR )
{ {
rt_kprintf("%s\t\t<DIR>\n", dirent->d_name); rt_kprintf("%s\t\t<DIR>\n", dirent->d_name);
} }
else else
{ {
rt_kprintf("%s\t\t%lu\n", dirent->d_name, s.st_size); rt_kprintf("%s\t\t%lu\n", dirent->d_name, s.st_size);
} }
} while (dirent != RT_NULL); } while (dirent != RT_NULL);
closedir(dir); closedir(dir);
} }
else else
{ {
rt_kprintf("open %s directory failed\n", path); rt_kprintf("open %s directory failed\n", path);
} }
rt_free(fullpath); rt_free(fullpath);
} }
#ifdef RT_USING_FINSH #ifdef RT_USING_FINSH