目标:
利用Linux命令获取当前目录下的文件和子目录名称,然后传递给C语言程序
由C语言程序对其进行排序,然后输出
相关知识:
1. dirent.h
LINUX系统下的一个头文件,在这个目录下/usr/include,为了获取某文件夹目录内容,所使用的结构体。引用头文件#include<dirent.h>
struct dirent
{
long d_ino; /* inode number 索引节点号 */
off_t d_off; /* offset to this dirent 在目录文件中的偏移 */
unsigned short d_reclen; /* length of this d_name 文件名长 */
unsigned char d_type; /* the type of d_name 文件类型 */
char d_name [NAME_MAX+1]; /* file name (null-terminated) 文件名,最长256字符 */
}
2. scandir()
#include <dirent.h>
int scandir( const char *dir,
struct dirent ***namelist,
int (*filter) (const void *b),
int ( * compare )( const struct dirent **, const struct dirent ** ) );
int alphasort(const void **a, const void **b);
int versionsort(const void **a, const void **b);
当函数成功执行时返回找到匹配模式文件的个数,如果失败将返回-1。
函数scandir扫描dir目录下以及dir子目录下满足filter过滤模式的文件,返回的结果是compare函数经过排序的,并保存在 namelist中。注意namelist是通过malloc动态分配内存的,所以在使用时要注意释放内存。alphasort和versionsort 是使用到的两种排序的函数。
readir()也可读取列表,但是无法实现排序
3、d_type的具体数值
以下内容转自http://blog.csdn.net/angle_birds/article/details/8503039
d_type表示档案类型:
enum
{
DT_UNKNOWN = 0,
# define DT_UNKNOWN DT_UNKNOWN
DT_FIFO = 1,
# define DT_FIFO DT_FIFO
DT_CHR = 2,
# define DT_CHR DT_CHR
DT_DIR = 4,
# define DT_DIR DT_DIR
DT_BLK = 6,
# define DT_BLK DT_BLK
DT_REG = 8,
# define DT_REG DT_REG
DT_LNK = 10,
# define DT_LNK DT_LNK
DT_SOCK = 12,
# define DT_SOCK DT_SOCK
DT_WHT = 14
# define DT_WHT DT_WHT
};
环境及软件:Ubuntu ,GCC
附上源码:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <dirent.h>
#include <string.h>
#include <sys/stat.h>
void print_dir(char *path, int depth)
{
struct dirent **name_list;
int n = scandir(path,&name_list,0,alphasort);
if(n < 0)
{
printf( "scandir return %d \n",n);
}
else
{
int index=0;
while(index < n)
{
printf("name: %s\n", name_list[index]->d_name);
free(name_list[index++]);
}
free(name_list);
}
}
int main(int argc, char* argv[])
{
char *now_dir, pwd[2]=".";
if (argc != 2)
{
now_dir=pwd;
}
else
{
now_dir=argv[1];
}
printf("Directory scan of %s\n",now_dir);
print_dir(now_dir,0);
printf("Finish.\n");
exit(0);
}
---------------------
版权声明:本文为CSDN博主「伟大的鸡蛋」的原创文章,遵循CC 4.0 by-sa版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/weixin_42730380/article/details/81103243