学习了LINUX停用C语言遍历文件夹,一些心得

学习了LINUX下用C语言遍历文件夹,一些心得

struct dirent中的几个成员:

d_type:4表示为目录,8表示为文件

d_reclen:16表示子目录或文件,24表示非子目录

d_name:目录或文件的名称

具体代码如下,仅供参考
#include
#include
#include

void List(char *path)
{
struct dirent* ent = NULL;
DIR *pDir;
pDir=opendir(path);
        if(pDir==NULL) printf("open dir faild\n");
        else printf("open dir ok %s\n",path);
while (NULL != (ent=readdir(pDir)))
{
         //     printf("ent->d_reclen:%d\n",ent->d_reclen);
         //     printf("ent->d_type:%d\n",ent->d_type);
if (ent->d_reclen==24)
{
if (ent->d_type==8)
printf("%s\n", ent->d_name);
else
{
printf("子目录:%s\n",ent->d_name);
List(ent->d_name);
printf("返回%s\n",ent->d_name);
}
}
}
}

int main(int argc, char *argv[])
{
List(argv[1]);
return 0;
}

1楼u011493281昨天 16:42
最好不要用数字比较,man readdir可以看到很多。n DT_BLK This is a block device.n DT_CHR This is a character device.n DT_DIR This is a directory.n DT_FIFO This is a named pipe (FIFO).n DT_LNK This is a symbolic link.n DT_REG This is a regular file.n DT_SOCK This is a UNIX domain socket.n DT_UNKNOWN The file type is unknown.n菜鸟意见供参考。