[linux应用编程]找寻目录中所有的文件

功能分析

描述

找寻目录下的所有的文件名称,包括子目录中的文件。

目录操作API

DIR *opendir(const char *name);	// 打开一个目录
struct dirent *readdir(DIR *dirp);	// 按照循序读取目录中的5条目,保存到struct dirent

struct dirent 结构体用于指向目录条目,结构体具体内容如下:
struct dirent 
{
	ino_t d_ino; /* inode编号 */ 
	off_t d_off; /* not an offset; see NOTES */ 
	unsigned short d_reclen; /* length of this record */ 
	unsigned char d_type; /* type of file; not supported by all filesystem types */ 
	char d_name[256]; /* 文件名 */ 
};

功能实现流程

该功能具体思路是,通过opendir打开相对应的目录,再由readdir逐条分析目录流中的条目。分析目录流中的条目,主要是通过struct dirent 结构体中的d_type(文件类型),d_name(名称)。

首先目录中的’.’ , ‘…‘是表示当前目录和上一级目录,因此可以忽略,其次剩下的则为文件和子目录,因此遇到的目录条目是文件,那我们就可以找到并打印,如果是子目录,那么可以使用相同的方式,打开子目录,将’.’ , '…'忽略,再判断是否为文件和子目录。如此循环直至读完整个目录。

实现具体程序

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include <dirent.h>
#include <stdlib.h>

void print_file_name(const char *dir)
{
    DIR *dirp;
    struct dirent *term;
    
    dirp = opendir(dir);
    if (NULL == dirp)
    {
        perror("opendir error");
        exit(-1);
    }

    // 循环读
    while (NULL != (term = readdir(dirp)))
    {
        // 当前目录和上一层目录不进行打印
        if (strcmp(term->d_name, ".") == 0 ||
            strcmp(term->d_name, "..") == 0)
        {
            continue;
        }

        // 判断是否为目录
        if (term->d_type == 4)
        {
            print_file_name(term->d_name);
        }
        else
        {
            printf("%s\n", term->d_name);
        }
    }   
}


int main(int argc, char *argv[])
{
    struct stat dir_stat;
    int ret = -1;
    
    // 首先判断参数个数
    if (argc != 2)
    {
        perror("参数个数错误\r\n");
        exit(0);
    }

    // 判断参数1是否为目录
    ret = stat(argv[1], &dir_stat);
    if (ret < 0)
    {
        perror("stat error");
        exit(0);
    }

    if ((dir_stat.st_mode & S_IFMT) != S_IFDIR)
    {
        perror("参数1 不是目录");
        exit(0);
    }

    // printf("argvp[1] = %s\r\n", argv[1]);

    print_file_name(argv[1]);

    return 0;
}

总结

通过系统编程获取linux目录中所有文件主要是需要对opendir()和readdir()的使用,以及struct dirent结构体中的成员的理解。以及递归思想的掌握。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值