Chinaunix首页 | 论坛 | 博客
  • 博客访问: 317968
  • 博文数量: 63
  • 博客积分: 2344
  • 博客等级: 大尉
  • 技术积分: 628
  • 用 户 组: 普通用户
  • 注册时间: 2009-05-13 11:09
个人简介

有一种沉默叫霸气,有一种内敛叫个性,有一种简单叫深遂,有一种不屑叫自我

文章分类

全部博文(63)

文章存档

2013年(10)

2012年(12)

2011年(1)

2010年(9)

2009年(31)

分类: LINUX

2013-12-05 09:19:54

Linux C中提供了读取文件夹函数,因为在项目中使用到,所以,总结一下。

1 opendir + readdir
打开文件夹,按序读取文件夹中的内容
#include
#include
DIR *opendir(const char *name);

int readdir(unsigned int fd, struct dirent *dirp, unsigned int count);
struct dirent
{
    long d_ino;                /*inode number*/
    off_t d_off;                /*offset to this dirent*/
    unsigned short d_reclen;    /*length of this d_name*/
    char d_name[NAME_MAX + 1]; /*filename (null-terminated)*/
}

eg:
struct dirent *direntPtr;
DIR *dir;
if ((dir = opendir(dirPath) ) == NULL)
{
    printf("Error: open %s directory failed.\n" dirPath);
    return -1;
}

while ( (direntPtr = readdir(dir) ) != NULL )
{
    printf("fileName \t %s\n", direntPtr->d_name);
}
closedir(dir);

该方法适合读取指定文件下的内容,读取的顺序时按照d_ino顺序,所以,不同的机器读取同一个公共文件夹的文件顺序可能会不一致。

2 scandir
读取文件夹中所有filter返回值不为0的文件,并且按照compar规则排序
#include
int scandir(const char *dir, struct dirent **namelist,
               int(*filter)(const struct dirent *),
               int(*compar)(const struct dirent **, const struct dirent **) );

int alphasort(const void *a, const void *b);        /* 使用strverscmp比较(*a)->d_name  (*b)->d_name */
int versionsort(const void *a, const void *b);      /* 使用strcoll比较(*a)->d_name (*b)->d_name */

eg:
int filterTxt(const struct dirent *dir)
{
    return strstr(dir->d_name, ".txt") != NULL;
}

struct dirent **fileList;
int fileNum = 0;
if ( (fileNum = scandir(dirpath), &fileList, filterTxt, alphasort) ) < 0 )
{
    printf("Error: scandir %s failled\n", dirpath);
    return -1;
}

while(fileNum--)
{
    printf("Reading %s\n, fileList[fileNum]->d_name);
    free(fileList[fileNum]);
}
free(fileList);

该方法能够按照你的要求过滤文件并且排序

3 ftw
递归遍历dirpath中所有目录,每进入一个目录调用一次fn, fpath是当前目录。只要fn返回0,则递归进入下一层
#include
int ftw(const chat *dirpath,
          int (*fn) (const char *fpath, const struct stat *sb, int typeflag),
          int nopenfd);
typeflag:
FTW_F: 一般文件
FTW_D: 目录
FTW_NDR: 不可读取目录,不进行遍历
FTW_SL: 符号链接
FTW_NS: 无法获取stat
nopenfd:
遍历文件时打开文件数

eg:
int getDir(const char *file, const struct stat *sb, int flag)
{
    if(flag == FTW_D)
        printf("directory: %s\n", file);
    return 1;
}

int flag = 0;
DIR * dir;
if ((dir = opendir(dirpath)) == NULL)
{
    printf("Error: opendir %s failed\n", dirpath);
     return -1;
}

flag = ftw(dirpath, getDir, 500);
printf("return value %d\n", flag);
closedir(dir);

该方法可以递归遍历所有目录,并按照条件输出


阅读(1751) | 评论(0) | 转发(0) |
0

上一篇:VIM小结

下一篇:没有了

给主人留下些什么吧!~~