DIR dirp对目录的操作

本文介绍了如何使用C语言中的DIR函数系列(opendir, readdir, closedir)来遍历文件目录,并结合stat函数获取文件详细信息。通过示例代码展示了打开目录、读取文件名并筛选特定文件的过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >




DIR函数以及dirp函数
DIR* opendir(const char*pathname),即打开文件目录,返回的就是指向DIR结构体的指针。
返回该指针以后,就可以被以下函数来使用了,
struct dirent *readdir(DIR *dp)
int closedir(DIR *dp)
long telldir(DIR *dp)


要知道dirent结构体是什么样的:
struct dirent
{
long d_no;//索引节点号
...
char d_name;//文件名

}
通过readdir 函数读取的文件名存放到dirent结构体的d_name成员中,
而函数stat
int stat(const char *filename,struct stat *buf);的作用就是获取d_name的文件详细信息,存储在stat结构体中。
stat结构体如下
struct stat{
time_t st_atime;//最后一次访问该文件的时间
time_t st_mtime;//最后一次修改该文件的时间
time_t st_ctime;//最后一次改变该文件状态的时间
...

}


获取一个文件信息的步骤如下
opendir打开目录,返回指向该目录下所有文件的dirent结构体d。
接着,遍历d,获取每个文件的详细信息,存储在stat结构体e中。


实战例子
int OpenDir(vector<string> & fileNameVec,const string &tmp_path)
{

DIR* dp;
struct dirent* dirp;
    if((dp = opendir(tmp_path.c_str())) == NULL)
    {
    perror( "Open dir error" );
    return -1;
    }

    while ((dirp = readdir(dp)) != NULL)
    {
        if (strcmp( dirp->d_name, ".") == 0 || strcmp(dirp->d_name,"..") == 0)
        {
        continue;
        }
       
        if (strstr( dirp->d_name,.DT) == NULL)
        {
        continue;
        }

    string tmpfileName(dirp->d_name);
    fileNameVec.push_back(tmpfileName);
        if (fileNameVec.size()>10)                  //一次传输10个
        {
        closedir(dp);
        return 1;
        }
    }
closedir(dp);
return 1;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值