在使用文件系统中,想获某一个目录下的文件,或者在使用液晶显示的时候,想把某一个目录下的文件和文件夹都显示出来,应该怎么做?
我个人查看了一下ls指令,但是内部具体的函数怎么用没看懂,也没有相关的说明,现在急需实现查看目录下文件的功能,希望RT-thread团队能给出点好的方法。十分感谢!
ls的源代码如下,不需要看懂,只需要直接调用,不就可以打印目录下的所有文件了吗?
void ls(const char *pathname)
{
struct stat stat;
int length;
char *fullpath, *path;
fullpath = NULL;
if (pathname == NULL)
{
#ifdef DFS_USING_WORKDIR
/* open current working directory */
path = rt_strdup(working_directory);
#else
path = rt_strdup("/");
#endif
if (path == NULL)
return ; /* out of memory */
}
else
{
path = (char *)pathname;
}
/* list directory */
if (dfs_file_open(&fd, path, O_DIRECTORY) == 0)
{
rt_kprintf("Directory %s:\n", path);
do
{
memset(&dirent, 0, sizeof(struct dirent));
length = dfs_file_getdents(&fd, &dirent, sizeof(struct dirent));
if (length > 0)
{
memset(&stat, 0, sizeof(struct stat));
/* build full path for each file */
fullpath = dfs_normalize_path(path, dirent.d_name);
if (fullpath == NULL)
break;
if (dfs_file_stat(fullpath, &stat) == 0)
{
rt_kprintf("%-20s", dirent.d_name);
if (S_ISDIR(stat.st_mode))
{
rt_kprintf("%-25s\n", "<DIR>");
}
else
{
rt_kprintf("%-25lu\n", stat.st_size);
}
}
else
rt_kprintf("BAD file: %s\n", dirent.d_name);
rt_free(fullpath);
}
}
while (length > 0);
dfs_file_close(&fd);
}
else
{
rt_kprintf("No such directory\n");
}
if (pathname == NULL)
rt_free(path);
}