在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. 最后一个非零数字(POJ 1604、POJ 1150、POJ 3406)

    POJ中有些问题给出了一个长数字序列(即序列中的数字非常多),这个长数字序列的生成有一定的规律,要求求出这个长数字序列中某个位上的数字是多少.这种问题通过分析,找出规律就容易解决. 例如,N!是一个非 ...

  2. css 动态导入css文件 @import 动态js加载 都是静态的

    @import "http://apps.bdimg.com/libs/bootstrap/3.3.4/css/bootstrap.css" /*-防止各大cdn公共库加载地址失效 ...

  3. xamarin.forms 绑定页面里指定元素的某个属性值

    {Binding Source={x:Reference elementName}, Path=BindingContext.propertyname, Mode=OneWay} elementNam ...

  4. Duplicate fragment name ERROR Jetty Maven Plugin

    http://stackoverflow.com/questions/5802096/duplicate-fragment-name-error-jetty-maven-plugin 4down vo ...

  5. ubuntu 网卡配置

  6. must have same number of columns as the referenced primary key

    在使用Hibernate实现多对多的测试过程中遇到了这个问题 解决的方法: 将黄色字段的内容添加进去 <set name="customerSet" table=" ...

  7. 正确地使用Context

    Context应该是每个入门Android开发的程序员第一个接触到的概念,它代表当前的上下文环境,可以用来实现很多功能的调用,语句如下. //获取资源管理器对象,进而可以访问到例如 string, c ...

  8. MSYS2 使用

    在Windows下编译mongo-c-driver 1.3.x 在Windows下编译mongo-c-driver 1.3.x 1.安装 MSYS2https://sourceforge.net/pr ...

  9. show()的几种方法

    1 show()方法和hide()方法 $("selector").show()  从display:none还原元素默认或已设置的display属性$("selecto ...

  10. C++操作MYSQL遇到的一些问题

    首先 我使用的是 vcpkg<不知道的可以进行百度 可以剧透一下,这个对Visual Studio使用一些C++的轮子太方便了, 上面是我装的一些库<大大安利vcpkg 安装时一定要使用p ...