在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. mac vim编辑器常用操作快捷方式

    0 行首$ (shift+6)行尾gg 文首G(shift+g) 文尾A(Shift+a)文尾,并编辑ctrl+f 向上翻页ctrl+b 向下翻页ctrl+u 向上翻半页ctrl+d 向下翻半页数字+ ...

  2. vue 表单操作

    <form class="mian__form" @submit.prevent="submit">     <ul>         ...

  3. js 鼠标拖拽元素移动

    <!DOCTYPE html><html> <head> <title> </title> <style media="sc ...

  4. 全国高校绿色计算大赛 预赛第三阶段(Python)(随机数)

    只提交了随机数 (真心不会 T-T ) import csv import random import pandas as pd import numpy as np # 预测结果文件:src/ste ...

  5. Python模块 shelve xml configparser hashlib

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

  6. python爬虫(三)

    Requests模块 这个库的标准文档有个极其幽默的地方就是它的中文翻译,我就截取个开头部分,如下图: 是不是很搞笑,在正文中还有许多,管中窥豹,可见一斑.通过我的使用,感觉Requests库的确是给 ...

  7. Matlab学习笔记(四)

    二.MATLAB基础知识 (六)字符串 字符串的创建和简单操作 用单引号对括起来的一系列字符的组合,每个字符是一个元素,通常通过两个字节来存储 表2-22    字符串常见操作函数(e_two_37. ...

  8. xtu summer individual-4 D - Martian Strings

    Martian Strings Time Limit: 2000ms Memory Limit: 262144KB This problem will be judged on CodeForces. ...

  9. vue2.0一个书城实例

    gitHub克隆地址 git clone https://github.com/Webxiaoyaun/vue-book.git 点击去Github下载 ## 一个书城 ## 有增加,修改,缓存,懒加 ...

  10. org.osgi.framework.BundleException: Exception in org.eclipse.core.resources.ResourcesPlugin.start()

    http://freestyle21.cn 不知什么时候,启动eclipse的时候就一直不行,说是an error ..我查了下log 报错:org.osgi.framework.BundleExce ...