在Unix/Linux系统中,要获取一个指定目录下所有的文件或文件夹,一般用dirent.h(POSIX标准定义的目录操作头文件)。

一、数据类型

在头文件<dirent.h>中定义了两种主要的数据类型。

DIR:代表一个目录流的结构体。

struct __dirstream
{
void *__fd; /* 'struct hurd_fd' pointer for descriptor.*/
char *__data; /* Directory block. */
int __entry_data; /* Entry number `__data' corresponds to.*/
char *__ptr; /* Current pointer into the block.*/
int __entry_ptr; /* Entry number `__ptr' corresponds to.*/
size_t __allocation; /* Space allocated for the block.*/
size_t __size; /* Total valid data in the block.*/
__libc_lock_define (, __lock) /* Mutex lock for this structure.*/
}; typedef struct __dirstream DIR;

struct dirent:包含一个文件或目录信息的结构体。

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) 文件名,最长255字符 */
}

二、函数原型

DIR* opendir(const char* dirname);
/* 打开一个目录:
成功 - 返回指向DIR类型对象的指针。
失败 - 返回NULL */ int closedir(DIR *dirp);
/* 关闭目录流:
成功 - 返回0
失败 - 返回-1 */ struct dirent *readdir(DIR *dirp);
/* 读取目录流:
成功 - 返回指向struct dirent对象的指针,当前位置向后移。
失败 - 返回NULL(出错或流末尾) */ int readdir_r(DIR *dirp, struct dirent *entry, struct dirent **result);
/* 读取目录流:用 dirp 当前位置的目录项初始化entry,并让 result 指向 entry。
成功 - 返回0
失败 - 返回error number */ void rewinddir(DIR *dirp);
/* 重置目录流的位置到开头 */ void seekdir(DIR *dirp, long int loc);
/* 设置目录流的位置,设置以后readdir()会读取到loc位置的目录项。 */ long int telldir(DIR *dirp);
/* 返回目录流的当前位置 */

三、示例代码

下面是一段 C 代码,输出指定目录下的所有文件或目录名:

#include<stdio.h>
#include<dirent.h> int main()
{
DIR *dp;
struct dirent *dirp;
char dirname[256]; printf("Please input a directory: ");
scanf("%s",dirname);
if((dp = opendir(dirname)) == NULL)
printf("Can't open %s\n", dirname); while((dirp = readdir(dp)) != NULL)
printf("%s\n", dirp->d_name); closedir(dp);
return 0;
}

C++代码:

#include<iostream>
#include<string>
#include<dirent.h>
using namespace std; int main()
{
string dirname;
DIR *dp;
struct dirent *dirp; cout << "Please input a directory: ";
cin >> dirname;
if((dp = opendir(dirname.c_str())) == NULL)
cout << "Can't open " << dirname << endl; while((dirp = readdir(dp)) != NULL)
cout << dirp->d_name << endl; closedir(dp);
return 0;
}

有些情况下,我们只要输出文件而不需要文件夹(目录),这时可以通过dirent结构体中的d_type进行过滤。d_type表示类型,4表示目录,8表示普通文件,0表示未知设备

while((dirp = readdir(dp)) != NULL)
if(dirp->d_type == 8) // 只输出文件名,不输出目录名
cout << dirp->d_name << endl;

如果需要查找指定类型(特定后缀)的文件,可以使用C++11的正则表达式进行匹配:

// #include<regex>
regex reg_obj(".*\.doc", regex::icase);
while((dirp = readdir(dp)) != NULL)
if(regex_match(dirp->d_name, reg_obj)) // regex_match()匹配
cout << dirp->d_name << endl;

另外,Unix/linux下提供了POSIX标准的正则库regex.h

个人站点:http://songlee24.github.com

【Unix编程】C/C++获取目录下文件或目录的更多相关文章

  1. Centos-显示目录或者目录下文件信息-ls

    ls 显示指定目录信息或指定目录下文件和目录信息,后边不跟文件目录路径信息默认为当前工作目录 默认显示输出信息的总行数统计数 相关参数 -a 显示所有文件或子目录,包含隐藏文档 # linux中以 . ...

  2. python生成器 获取 目录下文件

    # os.walk()和os.list 都是得到所有文件的列表, 如果目录下文件特别多, 上亿了, 我们就需要生成器的方式获取 # 要求目录下面没有目录, 会递归到子目录下面找文件, (如果有子目录可 ...

  3. IO流-获取指定目录下文件夹和文件对象【File类】

    一.运用File类实现获取指定目录下文件夹和文件对象 1.File类 2.方法: 获取文件绝对路径 :getAbsolutePath 案例: import java.io.File; /** * 获取 ...

  4. C# 获取目录下文件

    using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; usin ...

  5. Linux中/proc目录下文件详解

    转载于:http://blog.chinaunix.net/uid-10449864-id-2956854.html Linux中/proc目录下文件详解(一)/proc文件系统下的多种文件提供的系统 ...

  6. Linux中/proc目录下文件详解(转贴)

      转载:http://www.sudu.cn/info/index.php?op=article&id=302529   Linux中/proc目录下文件详解(一) 声明:可以自由转载本文, ...

  7. python 获取当前目录下文件(转)

    今天继续整理原来写的 python 代码,下面是获取文件信息的 python 处理代码. 获取指定目录下文件的文件名以及文件的数量,然后列出其中还存在的目录名称: #!/usr/bin/env pyt ...

  8. java 获取classpath下文件多种方式

    java 获取classpath下文件多种方式 一:properties下配置 在resources下定义server.properties register.jks.path=classpath\: ...

  9. linux获得目录下文件个数

    获得当前目录下文件个数赋值给变量panonum: panonum=$(ls -l |grep "^-" | wc -l) 获取指定目录下文件个数赋值给指定变量: panonum=$ ...

随机推荐

  1. Android(java)学习笔记187:多媒体之SurfaceView

    1. SurfaceView:     完成单位时间内界面的快速切换(游戏界面流畅感). 我们之前知道一般的View,只能在主线程里面显示,主线程中更新UI.但是SurfaceView可以在子线程中里 ...

  2. Python tldextract模块

    最新发布的 PyPI: pip install tldextract 或者最新的开发版本: pip install -e 'git://github.com/john-kurkowski/tldext ...

  3. ArrayList中removeAll和clear的区别(无区别)

    removeAll会直接调用此方法,传入list和false,因中间的逻辑都不会走(如果由retainAll方法调用,则会走这些逻辑判断),所以只需要看finaly中的最后一个if条件,w=0,通过循 ...

  4. Web项目ConcurrentModificationException异常

    后台SSH在做Session删除的时候,遇到了ConcurrentModificationException异常. 参考资料:http://blog.csdn.net/idesvo/article/d ...

  5. EZOJ 宝石迷阵 建图+网络流匹配

    题面: 封印恶魔的地方可以看作是一个 n*m 的矩形,包含了 n*m 个祭坛,并且其 中有一些祭坛已经损坏了. 如果 i+j 为偶数,那么第 i 行第 j 列的祭坛只要没有损坏,就一定会封印有一个恶魔 ...

  6. Python模块 shelve xml configparser hashlib

    常用模块1. shelve 一个字典对象模块 自动序列化2.xml 是一个文件格式 写配置文件或数据交换 <a name="hades">123</a>3. ...

  7. 安装php扩展(以swoole)为例

    一.下载swoole到/usr/local/src目录下,操作 git clone https://gitee.com/swoole/swoole.git; 二.cd swoole,phpize(如果 ...

  8. IDEA基本使用及配置(2)

    IDEA配置:File >> Setiings进入配置界面 1.主题配置:默认两种主题,黑色.白色,可以自己在网上下载,然后File >> Import Setiings导入, ...

  9. vector元素的删除 remove的使用 unique的使用

    在vector删除指定元素可用以下语句 : v.erase(remove(v.begin(), v.end(), element), installed.end()); 可将vector中所有值为el ...

  10. Springboot开启事务

    参考资料: https://blog.csdn.net/message_lx/article/details/77584847